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

1

9

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.

Frazzled answered 2/12, 2012 at 19:48 Comment(0)
J
15

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.

Jenny answered 2/12, 2012 at 20:2 Comment(6)
Thanks for the hint. I have not made it to work yet. I can't figure out what is the best placement for this snippet. I have it in a property setter, but I see not effect on my grid.Frazzled
What I expected was to remove only the row for the instance that has ShowHidden = false, but it removes the row from all instances. I will accept the answer as it did kinda what I need.Frazzled
The code changes the BrowsableAttribute, but I don' t see the change in grid...how can I see changes runtime?Cramp
@FrancescoDS: You should be able to see changes at runtime. Please post a new question if you have issues with this approach. Based on the number of upvotes, I'd assume it worked for others.Jenny
I had to put another line at the bottom of the code to make this work, something like: descriptor.SetValue(this, attrib); I think the componentchange/changing sequence takes effect after the setValueis called on the base object.Charismatic
@ja2 The reason it was hiding all your properties is because this only works when all the properties have a Browsable attribute. The source link mentions this issue.Ysabel

© 2022 - 2024 — McMap. All rights reserved.