Issue with custom TypeConverter and nested properties in the designer

拜拜、爱过 提交于 2021-01-27 21:52:17

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/3568341/issue-with-custom-typeconverter-and-nested-properties-in-the-designer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!