问题
Please read entire question first to understand where I would have the ability to reset the default value of a property.
When defining a custom class that can be visually designed, one can implement a collections editor to modify properties which are lists, arrays, collections, using the following pattern:
[Editor(typeof(CollectionEditor), typeof(UITypeEditor)),
DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public ElementCollection Elements
{
get;
}
Editing the Elements
property of this class will now launch a CollectionEditor
dialog, with a list of members on the left and a PropertyGrid
on the right.
The problem is, it appears that context menus are disabled for this property grid. Therefore, I cannot right click on a property to 'reset' its value to default, despite having a [DefaultValue]
attribute defined.
Yet, the DefaultValue
attribute is recognized, because the property is not serialized (and correctly displayed in unbolded text within the grid).
I would like to know how to enable this context menu on the PropertyGrid
from the CollectionEditor
dialog:
or alternatively, any way (hot key, etc.) that can be implemented to be able to reset these collection item properties.
回答1:
You can create your own collection editor inheriting CollectionEditor class and then override CreateCollectionForm method, find property grid in the collection editor form and then register a ContextMenuStrip
containing a Reset menu item for property grid, then reset the property using ResetSelectedProperty:
public class MyCollectionEditor : CollectionEditor
{
public MyCollectionEditor() : base(typeof(Collection<MyElement>)) { }
protected override CollectionForm CreateCollectionForm()
{
var form = base.CreateCollectionForm();
var grid = form.Controls.Find("propertyBrowser", true).First() as PropertyGrid;
var menu = new ContextMenuStrip();
menu.Items.Add("Reset", null, (s, e) => { grid.ResetSelectedProperty(); });
//Enable or disable Reset menu based on selected property
menu.Opening += (s, e) =>
{
if (grid.SelectedGridItem != null && grid.SelectedObject != null &&
grid.SelectedGridItem.PropertyDescriptor.CanResetValue(null))
menu.Items[0].Enabled = true;
else
menu.Items[0].Enabled = false;
};
grid.ContextMenuStrip = menu;
return form;
}
}
And decorate your collection property this way:
[Editor(typeof(MyCollectionEditor), typeof(UITypeEditor))]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public Collection<MyElement> MyElements { get; private set; }
Following this approach you can simply add a separator, commands and description menus.
来源:https://stackoverflow.com/questions/35517211/how-to-enable-default-values-for-properties-in-a-collectioneditor-dialog