代码之家  ›  专栏  ›  技术社区  ›  WildCrustacean

设计器中的自定义类型转换器和嵌套属性出现问题

  •  2
  • WildCrustacean  · 技术社区  · 14 年前

    我正在尝试使用类型转换器向自定义控件添加嵌套属性,这是我的测试代码:

    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旁边甚至没有扩展框)。

    我的理解是,它应该递归地调用 GetProperties() 每个属性的方法,因此作为一个测试黑客 MessageBox.Show() TestNestedOptionConverter.GetProperties() 方法,我在设计器加载控件时看不到消息。这让我觉得 获取属性() 因为某种原因从未被设计师叫来。

    你知道我做错了什么吗?

    我正在使用Visual Studio 2008。

    1 回复  |  直到 14 年前
        1
  •  2
  •   Quartermeister    14 年前

    它无法显示对象的属性,因为该对象为空。尝试在UserControl1构造函数中创建一个新对象:

    public partial class UserControl1 : UserControl
    {
        public TestNestedOption TestOption { get; set; }
    
        public UserControl1()
        {
            InitializeComponent();
            TestOption = new TestNestedOption();
        }
    }
    

    此外,您可以使用 ExpandableObjectConverter 这和你写的完全一样。如果需要重写其他方法,您可能仍然希望从中继承。