How to enable Default Values for properties in a 'CollectionEditor' dialog

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:

public ElementCollection Elements

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.

Asked: February 20, 2016 by administrator
Tags: winforms
Posted Under: programming

2 Answers

You can create your own a custom editor inheriting CollectionEditor and then override CreateCollectionForm and add a ContextMenuStrip containing a Reset item, 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(); });         
         menu.Opening += (s, e) =>         
            if (grid.SelectedGridItem != null && grid.SelectedObject != null && grid.SelectedGridItem.PropertyDescriptor.CanResetValue(null))   
               menu.Items[0].Enabled = true;
               menu.Items[0].Enabled = false;         
            grid.ContextMenuStrip = menu;         
            return form;     

Answered: February 20, 2016 by irfankhan04

Post Answer