簡體   English   中英

在運行時(動態地)將EditorAttribute添加到對象的特殊屬性

[英]Adding EditorAttribute at Run-time (Dynamically) to an Object's special Property

如果我有一個無法更改其代碼的以下類,如何在運行時將EditorAttribute添加到s1

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

我嘗試了這種方法,但是它也向s2添加了EditorAttribute編輯器,但我不希望這樣。

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

我怎樣才能做到這一點?

您可以嘗試使用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的派生版本,但是實現起來很簡單

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM