2012-10-23 43 views
3

我有一個應用程序,利用PropertyGrid中的在C#/。NETC#的PropertyGrid上列表限制編輯<T>項

PropertGrid保持到如下所示的MyAppObject類/對象..

class MyAppObject 
{ 
    private List<MyObject> oItems; 

    public List<MyObject> Items 
    { 
     get { return this.oItems; } 

    } 

} 

到目前爲止,它運行良好,很好,很簡單。我希望屬性網格允許用戶查看項目,但是當您在PropertyGrid中選擇屬性時,該對話框還允許添加更多List<MyObject> items

我不想這樣,我只想有能力顯示項目,而不是編輯它們。

我想通過不提供的setter(set { this.oItems = value; }):

like this

然後它wouldnt允許添加按鈕。

希望這是有道理的,屏幕截圖顯示對話框,我圈出了我想要刪除的按鈕。

感謝

回答

1

如果公開爲只讀列表,它應該做你需要的東西:

[Browsable(false)] 
public List<MyObject> Items 
{ 
    get { return this.oItems; } 
} 
// this (below) is the one the PropertyGrid will use 
[DisplayName("Items")] 
public ReadOnlyCollection<MyObject> ReadOnlyItems 
{ 
    get { return this.oItems.AsReadOnly(); } 
} 

注意,單個對象的成員(MyObject實例)仍然是可編輯的,除非你把它們裝飾成[ReadOnly(true)]

如您所見,設置者不需要添加/刪除/編輯項目。這是因爲網格仍然可以完全訪問.Add.Remove和索引器(list[index])操作。

0

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

public class MyObjectEditor : CollectionEditor { 

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

    public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) { 

     return ((MyObject)context.Instance).Items; 
    } 
} 

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

[Editor(typeof(MyObjectEditor), typeof(UITypeEditor))] 
public List<MyObject> Items{ 
    // ... 
} 

參考:What's the correct way to edit a collection in a property grid

備選:

return new ReadOnlyCollection(oItems); 

return oItems.AsReadOnly();