【发布时间】:2016-04-03 12:18:11
【问题描述】:
我正在使用 PropertyGrid 来编辑集合。带有集合的对象定义如下:
class ObjWithCollection
{
[Editor(typeof(MyCustomCollectionEditor),typeof(UITypeEditor))]
public List<ItemBase> collection { get; set; } = new List<ItemBase>();//ItemBase is abstract
}
该集合包含两种类型的对象,派生自 ItemBase 类:Item1 和 Item2。这些类定义如下:
public abstract class ItemBase
{
public string Name { get; set; }
public ItemBase() { }
public ItemBase(string name) { Name = name; }
}
public class Item1:ItemBase
{
public Item1():base("Item 1 name"){}
}
[DisplayName("item2 test display name")]
public class Item2:ItemBase
{
public Item2() : base("item 2 name") { }
}
为了能够通过编辑器向集合添加新项目,我还定义了自定义集合编辑器类并重写 CreateNewItemTypes 以列出所有适合集合的类型:
class MyCustomCollectionEditor : CollectionEditor
{
public MyCustomCollectionEditor(Type type) : base(type){}
protected override Type[] CreateNewItemTypes()
{
return new Type[] { typeof(Item1), typeof(Item2) };
}
}
然后我将我的自定义编辑器绑定到具有 Editor 属性的 ObjWithCollection.collection 属性(请参阅 ObjWithCollection.collection 定义)。
这很好用,我可以编辑我的收藏,包括添加新项目。添加按钮有一个下拉菜单,允许用户选择要添加的元素类型。 editor window http://i.share.pho.to/31d50d09_o.png
但在“添加”按钮下拉菜单中,名为“Item1”和“Item2”的项目我无法更改这些名称。我尝试了 DisplayName 属性,ToString 覆盖,但没有运气。
所以,问题是我如何为添加按钮菜单的元素输出自定义名称。
【问题讨论】:
标签: c# editor propertygrid