How to customize names in “Add” button dropdown in the PropertyGrid custom collection editor

╄→гoц情女王★ 提交于 2019-12-06 05:35:14

I don't think this is possible directly from the property grid's code. However, you can use a TypeDelegator to trick the system and force it to use for example your DisplayName attribute in lieu of the type's Name property it uses by default.

1) create a custom TypeDelegator, like this:

class MyTypeDelegator : TypeDelegator
{
    public MyTypeDelegator(Type delegatingType)
        : base(delegatingType)
    {
    }

    public override string Name
    {
        get
        {
            var dna = (DisplayNameAttribute)typeImpl.GetCustomAttribute(typeof(DisplayNameAttribute));
            return dna != null ? dna.DisplayName : typeImpl.Name;
        }
    }
}

2) modify CreateNewItemTypes() like this:

    protected override Type[] CreateNewItemTypes()
    {
        return new Type[] { new MyTypeDelegator(typeof(Item1)), new MyTypeDelegator(typeof(Item2)) };
    }

Now, you should see the display names instead of the name in the menu.

You can also change the text by hooking into CollectionForm's Controls (Ugly, Not Recommended, DO NOT USE IN PRODUCTION, Note that it could be changed and obsolete in anytime)

 public sealed class OutputItemEditor : CollectionEditor // need a reference to System.Design.dll
{
    public OutputItemEditor(Type type)
        : base(type)
    {
    }

    protected override Type[] CreateNewItemTypes()
    {
        return new[] { typeof(StaticOutputItem), typeof(VariableOutputItem),typeof(ExpressionOutputItem) };
    }

    protected override CollectionForm CreateCollectionForm()
    {
        CollectionForm collectionForm = base.CreateCollectionForm();            
        collectionForm.Text = "Output Collection";

        //Modify the Add Item Button Text
        try
        {
            //You can use "collectionForm.Controls.Find("addButton",true)" here also
            foreach (ToolStripItem item in collectionForm.Controls[0].Controls[1].Controls[0].ContextMenuStrip.Items)
            {
                //Since Item Names are the Type Names
                switch (item.Text)
                {
                    case "StaticOutputItem":
                        item.Text = "Static Output Item";
                        break;
                    case "VariableOutputItem":
                        item.Text = "Variable Output Item";
                        break;
                    case "ExpressionOutputItem":
                        item.Text = "Expression Output Item";
                        break;
                    default:
                        break;
                }
            }
        }
        catch (Exception)
        {
        }

        return collectionForm;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!