views:

34

answers:

1

I'm trying to add a nested property to my custom control using a TypeConverter, here is my test code:

public class TestNestedOptionConverter : TypeConverter
{
    public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context,
        object value, Attribute[] filter)
    {
        return TypeDescriptor.GetProperties(typeof(TestNestedOption));
    }

    public override bool GetPropertiesSupported(ITypeDescriptorContext context)
    {
        return true;
    }
}

[TypeConverter(typeof(TestNestedOptionConverter))]
public class TestNestedOption
{
    bool test1 = false;

    [Description("TestParam1")]
    public bool Test1
    {
        get { return test1; }
        set { test1 = value; }
    }

    [Description("TestParam2")]
    public int Test2 { get; set; }
}

public partial class UserControl1 : UserControl
{
    public TestNestedOption TestOption { get; set; }

    public UserControl1()
    {
        InitializeComponent();
    }
}

When I add the control to a form, I see the TestOption property in the designer property grid, but the sub-properties do not show up at all (there isn't even an expansion box next to TestOption).

My understanding of this is that it is supposed to sort of recursively call the GetProperties() method on each property, so as a test hack I put a MessageBox.Show() in the TestNestedOptionConverter.GetProperties() method, and I don't see the message when the designer loads the control. This makes me think that the overridden GetProperties() is never being called by the designer for some reason.

Any ideas about what I am doing wrong?

I'm using Visual Studio 2008.

A: 

It can't display properties for the object because the object is null. Try simply creating a new object in the UserControl1 constructor:

public partial class UserControl1 : UserControl
{
    public TestNestedOption TestOption { get; set; }

    public UserControl1()
    {
        InitializeComponent();
        TestOption = new TestNestedOption();
    }
}

Also, rather than writing a custom TypeConverter for this, you can just use ExpandableObjectConverter, which does exactly what you've written. If you need to override other methods, you still may want to inherit from it.

Quartermeister
Thank you, that is exactly what I was looking for.
bde