我有一个显示在属性网格中的类.其中一个属性是List<SomeType>.
设置代码的最简单/最正确的方法是什么,以便我可以通过属性网格添加和删除此集合中的项目,最好使用标准CollectionEditor.
错误的方法之一是这样的:
用户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
}
}
Run Code Online (Sandbox Code Playgroud)
这有点棘手; 该解决方案涉及完整的.NET框架的基础上(因为仅客户端框架不包括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;
}
}
Run Code Online (Sandbox Code Playgroud)
然后你必须用以下方法装饰你的财产EditorAttribute:
[Editor(typeof(SomeTypeEditor), typeof(UITypeEditor))]
public List<SomeType> Stuff {
// ...
}
Run Code Online (Sandbox Code Playgroud)
很长很复杂,是的,但它确实有效.当您单击集合编辑器弹出"确定",就可以再次打开它和值将保持.
注意:您需要导入的命名空间System.ComponentModel,System.ComponentModel.Design和System.Drawing.Design.