Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you control what is visible in a property grid at runtime?

I have a property grid displaying a list, for example of a class Person

[TypeConverter(typeof(ExpandableObjectConverter))]
public class Person
{
    public bool ShowHidden { get; set; }
    public string Name { get; set; }
    //[Browsable(false)]
    public string Hidden { get; set; }

    public override string ToString()
    {
        return string.Format("Person({0})", Name);
    }
}

The question is how do I control the Browsable() attribute at runtime such that when ShowHidden = false the Hidden line (highlighted yellow below) is omitted.

Screenshot

Thanks.

like image 227
John Alexiou Avatar asked Dec 02 '12 19:12

John Alexiou


1 Answers

Here is an example:

PropertyDescriptor descriptor=
  TypeDescriptor.GetProperties(this.GetType())["DataType"];
BrowsableAttribute attrib= 
  (BrowsableAttribute)descriptor.Attributes[typeof(BrowsableAttribute)]; 
FieldInfo isBrow = 
  attrib.GetType().GetField("browsable",BindingFlags.NonPublic | BindingFlags.Instance);
isBrow.SetValue(attrib,false);

Just replace DataType with your property name. Note, all properties must have the attribute being changed (in this case, Browsable). If one of the properties is missing the attribute, all of the class properties get the new attribute setting.

Code taken from here: Exploring the Behaviour of Property Grid.

like image 53
Neolisk Avatar answered Oct 25 '22 12:10

Neolisk