Search code examples
c#winformsdevexpresspropertygridsystem.componentmodel

Defining the Edit-Type (In-Place Editor) in Devexpress PropertyGrid.SelectedObject's Class


let's say i have this class

public sealed class OptionsGrid
{

   [Description("Teststring"), DisplayName("DisplaynameTest"), Category("Test")]
   public string Test { get; set; }
}

is there any chance to define which Edit (e.G. MemoEdit) should be used for this row in the class itself?

The Propertygrids SelectedObject is set like this

propertyGridControl1.SelectedObject = new OptionsGrid();

Solution

  • You can define your own attribute containing a type of the desired editor:

    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]
    public sealed class EditorControlAttribute : Attribute
    {
        private readonly Type type;
    
        public Type EditorType
        {
            get { return type; }
        }
    
        public EditorControlAttribute(Type type)
        {
            this.type = type;
        }
    }
    
    public sealed class OptionsGrid
    {
        [Description("Teststring"), DisplayName("DisplaynameTest"), Category("Test")]
        [EditorControl(typeof(RepositoryItemMemoEdit))]
        public string Test { get; set; }
    }
    

    Then you should set it in the PropertyGrid.CustomDrawRowValueCell as follows:

    private void propertyGrid_CustomDrawRowValueCell(object sender, DevExpress.XtraVerticalGrid.Events.CustomDrawRowValueCellEventArgs e)
    {
        if (propertyGrid.SelectedObject == null || e.Row.Properties.RowEdit != null)
            return;
    
        System.Reflection.MemberInfo[] mi = (propertyGrid.SelectedObject.GetType()).GetMember(e.Row.Properties.FieldName);
        if (mi.Length == 1)
        {
            EditorControlAttribute attr = (EditorControlAttribute)Attribute.GetCustomAttribute(mi[0], typeof(EditorControlAttribute));
            if (attr != null)
            {
                e.Row.Properties.RowEdit = (DevExpress.XtraEditors.Repository.RepositoryItem)Activator.CreateInstance(attr.EditorType);
            }
        }
    }
    

    See also (scroll to the bottom): https://documentation.devexpress.com/#WindowsForms/CustomDocument429

    EDIT: Perfomance improved.