设计器中的自定义TypeConverter和嵌套属性存在问题 [英] Issue with custom TypeConverter and nested properties in the designer

查看:60
本文介绍了设计器中的自定义TypeConverter和嵌套属性存在问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用TypeConverter将嵌套属性添加到自定义控件中,这是我的测试代码:

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();
    }
}

当我将控件添加到窗体时,我在设计器属性网格中看到了TestOption属性,但是子属性根本不显示(TestOption旁边甚至没有扩展框).

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).

我对此的理解是,应该对每个属性进行递归调用 GetProperties()方法,因此,作为测试工具,我放置了 MessageBox.Show() TestNestedOptionConverter.GetProperties()方法中,当设计器加载控件时,我没有看到此消息.这使我认为设计器出于某种原因从未调用过覆盖的 GetProperties().

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?

我正在使用Visual Studio 2008.

I'm using Visual Studio 2008.

推荐答案

由于该对象为null,因此无法显示该对象的属性.尝试简单地在UserControl1构造函数中创建一个新对象:

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.

这篇关于设计器中的自定义TypeConverter和嵌套属性存在问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆