Is there a PropertyGrid Collection Editor "Add" button event or override?
Asked Answered
B

1

2

Is there an event or a function that is triggered when the Windows Forms PropertyGrid Collection Editor "Add" button is clicked? (see image)

I'd like to add some custom code to run when this button is pressed.

I use a custom collection for a list of objects (CollectionBase). My constructor is called when the Add button is pressed, but I see no other functions in the call list where I could insert some custom code.

enter image description here

Barnwell answered 7/2, 2018 at 18:49 Comment(2)
Maybe. First, revisit your CollectionBase decision: Guidelines for Collections. I've done things with complex collections using a custom UITypeEditor. It would look for an Interface on the Type being created and make a call to the class to do whatever. I am not entirely sure that Prop Grid would use the UITypeEditor but it would be easy to find out.Brassy
Question that accomplishes something fairly similar: How do you create a custom collection editor form for use with the property grid?Battled
Q
5

There is no documented way, you'll have to use your own editor. But you can derive from the standard editor class. Here is an example of such a hack:

Define the custom editor attribute like this on the collection property:

[Editor(typeof(MyCollectionEditor), typeof(UITypeEditor))]
public List<Child> Children { get; }

With this editor code:

// CollectionEditor needs a reference to System.Design.dll
public class MyCollectionEditor : CollectionEditor
{
    public MyCollectionEditor(Type type)
        : base(type)
    {
    }

    protected override CollectionForm CreateCollectionForm()
    {
        CollectionForm form = base.CreateCollectionForm();
        var addButton = (ButtonBase)form.Controls.Find("addButton", true).First();
        addButton.Click += (sender, e) =>
            {
                MessageBox.Show("hello world");
            };
        return form;
    }
}

The add button is a simple Winforms button, so you can do anything with it.

Quiff answered 8/2, 2018 at 7:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.