2012-10-23 39 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();