2012-02-29 226 views
1

如果我有一個類似以下的代碼,我不能更改代碼,那麼如何在運行時將一個EditorAttribute添加到s1將運行時(動態)的EditorAttribute添加到對象的特殊屬性

class TestClass 
{ 
    public String s1 {get;set;} 
    public String s2 {get;set;} 
} 

這個方法我試過,但它增加了一個EditorAttribute編輯器s2太,我不希望出現這種情況。

TypeDescriptor.AddAttributes(
    typeof(String), 
    new EditorAttribute ( 
      typeof(MyUITypeEditor), 
      typeof(UITypeEditor))); 

我該怎麼做?

回答

0

您可以嘗試使用CustomTypeDescriptor來實現您自己的類的類型描述符,並覆蓋GetProperties方法以返回一組自定義屬性描述符,這將使您有機會添加任何您想要的屬性的自定義屬性。

一旦你有了這個自定義類型描述符,你就可以綁定該類的一個實例(可以將TestClass類的實例包裝到PropertyGrid控件中)。

類似以下內容:

public class TestClassTypeDescriptor : ICustomTypeDescriptor 
{ 
    private TestClass mInst; 

    public TestClassTypeDescriptor(TestClass inst) 
    { 
    mInst = inst; 
    } 

    //Implement ICustomTypeDescriptor 
} 


PropGridControl.SelectedObject = new TestClassTypeDescriptor(new TestClass()); 

您可能需要創建的PropertyDescriptorPropertyDescriptorCollection自己的衍生版本,但這些都是實現

很簡單