2013-04-08 46 views
2

我有一些公共领域的一类,我想显示在窗体上的PropertyGrid此字段:禁止收集

public class FileInfo 
{ 
    ... 

    [DisplayName("Messages")] 
    public Collection<MessageInfo> MessageInfos { get; set; } 
} 

的问题是,我也想禁用收集此类的某些情况下,所以用户甚至不能进入其编辑器。我需要从代码中,而不是从设计者那里获得。

即使我做这个领域只读通过添加属性[只读(真),将允许用户通过按下进入它的编辑(...):

enter image description here

+0

当你说设计师......你指的是Visual Studio中,你的程序,等等? – Jared 2013-04-08 04:08:19

回答

2

你可以做,如果你自定义一个UITypeEditor重写标准CollectionEditor,这样的事情:

public class FileInfo 
    { 
     [DisplayName("Messages")] 
     [Editor(typeof(MyCustomCollectionEditor), typeof(UITypeEditor))] 
     public Collection<MessageInfo> MessageInfos { get; set; } 
    } 

    public class MyCustomCollectionEditor : CollectionEditor // needs a reference to System.Design.dll 
    { 
     public MyCustomCollectionEditor(Type type) 
      : base(type) 
     { 
     } 

     public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) 
     { 
      if (DontShowForSomeReason(context)) // you need to implement this 
       return UITypeEditorEditStyle.None; // disallow edit (hide the small browser button) 

      return base.GetEditStyle(context); 
     } 
    } 
+0

谢谢,这正是我需要的。 – Andark 2013-04-09 03:36:34

0

添加一个布尔标志指示集合是否为只读:

public class FileInfo 
{ 
    ... 

    [DisplayName("Messages")] 
    public Collection<MessageInfo> MessageInfos { get; set; } 
    public bool IsReadOnly; 
} 

设置IsReadOnlytrue为要禁用这些实例。然后,您可以根据标志的状态启用/禁用UI。

+0

IsReadOnly将显示为另一个属性,它对MessageInfos没有意义。 – Andark 2013-04-08 04:03:44

+0

@andark - 如果您只是将IsReadOnly设置为公共字段而不是属性,它仍会显示吗?更新代码以反映这一建议。 – 2013-04-08 04:16:00

+0

如果它不是一个属性,它不会显示给用户,但我可以任何方式输入Collection的编辑器。 – Andark 2013-04-08 04:26:48

0

取决于您的程序设计。你可能会使用继承。你并没有真正提供有关谁可以访问你的对象等信息。随着缺乏细节,那么它需要在代码中,而不是设计师,这是一个简单的解决方案。或者你可能需要更强大的东西。

public class FileInfo 
{ 
    //... 
} 

public class FileInfoWithCollection : FileInfo { 
    [DisplayName("Messages")] 
    public Collection<MessageInfo> MessageInfos { 
      get; 
      set; 
    }  
} 

另一种选择可能是推出的Collection自己继承的副本将覆盖可以修改集合中的任何方法。如果没有更多的信息,并且收集是一种参考类型,我怀疑你会得到一个肯定的答案。

0

在属性的顶部添加ReadOnly属性。

[DisplayName("Messages")] 
[ReadOnly(true)] 
public Collection<MessageInfo> MessageInfos { get; set; } 

还没有测试过,希望它有效。

摘自this link