2010-11-10 63 views
2

我有一個顯示在屬性網格中的類。其中一個屬性是List<SomeType>在屬性網格中編輯集合的正確方法是什麼

設置代碼的最簡單/正確的方法是什麼,以便我可以通過屬性網格添加和刪除此集合中的項目,最好使用標準CollectionEditor

其中一個錯誤的方法是這樣的:

set not being called when editing a collection

用戶annakata建議我露出IEnumerable接口而不是一個集合。有人可以提供給我更多的細節嗎?

我有收集由get返回實際上並不指向我的類成員的額外複雜性,但建立在飛從其他成員,像這樣:

public List<SomeType> Stuff 
{ 
    get 
    { 
     List<SomeType> stuff = new List<SomeType>(); 
     //...populate stuff with data from an internal xml-tree 
     return stuff; 
    } 
    set 
    { 
     //...update some data in the internal xml-tree using value 
    } 
} 

回答

5

這是需要一點技巧之一;該解決方案涉及使用完整的.NET Framework進行構建(因爲僅客戶端框架不包括System.Design)。您需要創建的CollectionEditor自己的子類,並告訴它做什麼用的臨時集合UI完成它後:

public class SomeTypeEditor : CollectionEditor { 

    public SomeTypeEditor(Type type) : base(type) { } 

    public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) { 
     object result = base.EditValue(context, provider, value); 

     // assign the temporary collection from the UI to the property 
     ((ClassContainingStuffProperty)context.Instance).Stuff = (List<SomeType>)result; 

     return result; 
    } 
} 

然後,你必須來裝飾與EditorAttribute你的財產:

[Editor(typeof(SomeTypeEditor), typeof(UITypeEditor))] 
public List<SomeType> Stuff { 
    // ... 
} 

很長且令人費解,是的,但它的工作原理。在集合編輯器彈出框中單擊「確定」後,可以再次打開它,值將保留。

注意:您需要導入名稱空間System.ComponentModel,System.ComponentModel.Design和。

+0

謝謝,這工作得很好! – 2010-11-11 06:50:31

0

由於只要類型有一個公共的無參數的構造函數它應該只是工作

using System; 
using System.Collections.Generic; 
using System.Windows.Forms; 
class Foo { 
    private readonly List<Bar> bars = new List<Bar>(); 
    public List<Bar> Bars { get { return bars; } } 
    public string Caption { get; set; } 
} 
class Bar { 
    public string Name { get;set; } 
    public int Id { get; set; } 
} 
static class Program { 
    [STAThread] 
    static void Main() { 
     Application.EnableVisualStyles(); 
     Application.Run(new Form { 
      Controls = { new PropertyGrid { Dock = DockStyle.Fill, 
              SelectedObject = new Foo() 
     }}}); 
    } 
} 
+0

問題是,從'get'返回的集合只是一些從其他數據構建的臨時集合。我會編輯我的問題。 – 2010-11-10 14:17:27

相關問題