Skip to main content
A newer version of this page is available.
All docs
V18.2

Color Properties in Domain Components

  • 3 minutes to read

This topic demonstrates two approaches to store a System.Drawing.Color property value in the database using the Domain Components technology.

  1. The first approach is to implement a Value Converter.

    using System;
    using System.Drawing;
    using DevExpress.Xpo.Metadata;
    // ...
    public class ColorValueConverter : ValueConverter {
        public override Type StorageType {
            get { return typeof(Int32); }
        }
        public override object ConvertToStorageType(object value) {
            if(!(value is Color)) return null;
            Color color = (Color)value;
            return color.IsEmpty ? -1 : color.ToArgb();
        }
        public override object ConvertFromStorageType(object value) {
            if(!(value is Int32)) return null;
            Int32 argbCode = Convert.ToInt32(value);
            return argbCode == -1 ? Color.Empty : Color.FromArgb(argbCode);
        }
    }
    

    After that, decorate properties that are need to be converted with the ValueConverterAttribute and the converter will be called on each attempt to store or acquire a value of the System.Drawing.Color type.

    using DevExpress.ExpressApp.DC;
    using DevExpress.Persistent.Base;
    using DevExpress.Xpo;
    using System.Drawing;
    //...
    [DomainComponent, NavigationItem]
    public interface IMyColor {
        [ValueConverter(typeof(ColorValueConverter))]
        Color Color { get; set; }
    }
    
  2. Another approach is to convert the System.Drawing.Color type to System.Int32 on property implementation using Get_PropertyName and Set_PropertyName methods of the Domain Logic class, as shown below.

    using DevExpress.ExpressApp.DC;
    using DevExpress.Persistent.Base;
    using System.ComponentModel;
    using System.Drawing;
    //...
    [DomainComponent, NavigationItem]
    public interface IMyColor {
        [Browsable(false)]
        int PersistentColor { get; set; }
        [NonPersistentDc]
        Color Color { get; set; }
    }
    
    [DomainLogic(typeof(IMyColor))]
    public class MyColorLogic {
        public static Color Get_Color(IMyColor MyColor) {
            return Color.FromArgb(MyColor.PersistentColor);
        }
        public static void Set_Color(IMyColor MyColor, Color value) {
            MyColor.PersistentColor = value.ToArgb();
        }
    }
    

    Note

    If the type’s class does not have an appropriate conversion method (Color.ToArgb in this case), implement a Type Converter and use it any time you need a value conversion between the type you need to store and an ORM-friendly type.