2010-08-25 74 views
2

我试图用一个类型转换器嵌套属性添加到我的自定义控件定义TypeConverter以及嵌套属性,这里是我的测试代码:问题与设计师

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()方法,因此作为测试砍我在TestNestedOptionConverter.GetProperties()方法把MessageBox.Show(),我没有看到消息,当设计师加载控件。这使我认为被重写的GetProperties()永远不会被设计者出于某种原因调用。

任何关于我在做什么的想法都是错误的?

我正在使用Visual Studio 2008.

回答

2

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

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

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

此外,而不是写这个自定义类型转换器,你可以只使用ExpandableObjectConverter,这确实你写什么。如果你需要重写其他方法,你仍然可能想从它继承。

+0

谢谢,那就是我一直在寻找的。 – WildCrustacean 2010-08-30 14:14:05