How to create browseable class-properties in .NET / Visual studio

Maciej :

How I can make something like this in VS properties Window (collapsible multi properties):

enter image description here

I tried such code:

   Test z = new Test();

    [ Browsable(true)]
    public Test _TEST_ {
        get { return z; }
        set { z = value; }
    }

Where "Test" class is:

[Browsable(true)] 
public class Test {
    [Browsable(true)] 
    public string A { get;set; }
    [Browsable(true)] 
    public string B { get;set; }
}

But this gives me only grayed-out name of class

enter image description here

Max Play :

Alright, I got something to work that may satisfy your case.

To get a class to expand in the PropertyGrid, you have to add a TypeConverterAttribute to it, referencing the type of an ExpandableObjectConverter (or something else that derives from it).

[TypeConverter(typeof(ExpandableObjectConverter))]
public class Test
{
    [Browsable(true)]
    public string A { get; set; }
    [Browsable(true)]
    public string B { get; set; }
}

The only problem is that it now displays the type name (the return value of its ToString() method as the value of your class). You can either live with it (which you probably won't want to), change the ToString() return value to something more fitting or use a custom TypeConverter for that case.

I'll show you a quick implementation on how the latter could be done:

internal class TestConverter : ExpandableObjectConverter
{
    public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
    {
        if (destinationType == typeof(string))
            return "";
        return base.ConvertTo(context, culture, value, destinationType);
    }
}

And then you would write this, instead of what I wrote above:

[TypeConverter(typeof(TestConverter))]
public class Test
{
    [Browsable(true)]
    public string A { get; set; }
    [Browsable(true)]
    public string B { get; set; }
}

This just empties the information and prevents the user to enter some other value. You probably want to show something more descriptive which is completely up to you.
It is also possible to get information and parse it into useful values. A good example would be the location, which is an object of type Point visualized with [10,5] when X is 10 and Y is 5. When you enter new values they are parsed and set to the integers that are referenced by the original string.


Because I couldn't find much about the topic, I looked up some references in ReferenceSource, because it had to be done before. In my case, I peeked into ButtonBase and FlatButtonAppearance of WindowsForms to see how Microsoft did it, back in the day.

Hope I could help.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=368201&siteId=1