C# property grid, set browsable attribute to enumeration each item on runtime?

2.7k views Asked by At

I have question regarding c# property grid.

public enum xxx
{
    [Browsable(true)]
    aaa,
    [Browsable(false)]
    bbb,
    [Browsable(true)]
    ccc,
}

public class testObject {
    public xxx temp;

    public xxx test {
    get { return temp; }
    set { temp = value; }
}

How can I change the browsable attribute at run time?

For example, when btn1 is pressed, I want to set the browsable attribute to false for all, like this:

private void button1_Click(object sender, RoutedEventArgs e)
{
    object[] browsable;

    Type type = typeof(xxx);
    FieldInfo[] fieldInfos = type.GetFields();

    foreach (FieldInfo fieldInfo in fieldInfos)
    {
        browsable = fieldInfo.GetCustomAttributes(typeof(BrowsableAttribute), false);

        if (browsable.Length == 1)
        {
            BrowsableAttribute brAttr = (BrowsableAttribute)browsable[0];
            fieldInfo.SetValue(brAttr, false);
        }
    }
} 

but it causes an error.

1

There are 1 answers

1
USER87 On BEST ANSWER

you can change browsable property in this way...

 object[] browsable;

Type type = typeof(xxx);
FieldInfo[] fieldInfos = type.GetFields();
foreach (FieldInfo fieldInfo in fieldInfos)
{
    browsable = fieldInfo.GetCustomAttributes(typeof(BrowsableAttribute), false);

    if (browsable.Length == 1)
    {

        System.ComponentModel.PropertyDescriptorCollection pdc = System.ComponentModel.TypeDescriptor.GetProperties(fieldInfo);

        //Get property descriptor for current property
        System.ComponentModel.PropertyDescriptor descriptor = pdc[24];// custom attribute
        BrowsableAttribute attrib =
      (BrowsableAttribute)descriptor.Attributes[typeof(BrowsableAttribute)]; 
        FieldInfo isReadOnly =
         attrib.GetType().GetField("browsable", BindingFlags.NonPublic | BindingFlags.Instance);
        isReadOnly.SetValue(attrib, true);
    }
}

try this one this may helps you....