set not being called when editing a collection

2019-08-04 16:25发布

I have a class containing a collection property which I want to display and edit in a property grid:

[EditorAttribute(typeof(System.ComponentModel.Design.CollectionEditor), typeof(System.Drawing.Design.UITypeEditor))]
public List<SomeType> Textures
{
    get
    {
        return m_collection;
    }
    set
    {
        m_collection = value;
    }
}

However, when I try to edit this collection with the CollectionEditor, set is never called; why is this and how can I fix it?

I also tried to wrap my List<SomeType> in my own collection as described here:

http://www.codeproject.com/KB/tabs/propertygridcollection.aspx

But neither Add, nor Remove is being called when I add and remove items in the CollectionEditor.

1条回答
来,给爷笑一个
2楼-- · 2019-08-04 17:00

Your setter isn't being called because when you're editting a collection, you're really getting a reference to the original collection and then editting it.

Using your example code, this would only call the getter and then modify the existing collection (never resetting it):

var yourClass = new YourClass();
var textures = yourClass.Textures

var textures.Add(new SomeType());

To call the setter, you would actually have to assign a new collection to the Property:

var yourClass = new YourClass();
var newTextures = new List<SomeType>();
var newTextures.Add(new SomeType());

yourClass.Textures = newTextures;
查看更多
登录 后发表回答