在编辑集合时设置不被调用

时间:2010-11-10 13:44:03

标签: c# collectioneditor

我有一个包含集合属性的类,我想在属性网格中显示和编辑它:

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

但是,当我尝试使用CollectionEditor编辑此集合时,永远不会调用set;为什么会这样,我该如何解决?

我还尝试将List<SomeType>包装在我自己的集合中,如下所述:

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

但是,当我在Add中添加和删除项目时,RemoveCollectionEditor都没有被调用。

1 个答案:

答案 0 :(得分:3)

你的setter没有被调用,因为当你编辑一个集合时,你真的得到了对原始集合的引用,然后编辑它。

使用您的示例代码,这只会调用getter然后修改现有的集合(从不重置它):

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

var textures.Add(new SomeType());

要调用setter,您实际上必须为Property添加一个新集合:

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

yourClass.Textures = newTextures;
相关问题