【问题标题】:set not being called when editing a collection编辑集合时未调用设置
【发布时间】:2011-05-07 21:38:26
【问题描述】:

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

[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&lt;SomeType&gt; 包装在我自己的收藏中,如下所述:

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

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

【问题讨论】:

  • 好问题,突出了一个常见的误解。

标签: c# collectioneditor


【解决方案1】:

您的 setter 没有被调用,因为当您编辑集合时,您实际上是在获取对原始集合的引用,然后对其进行编辑。

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

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

var textures.Add(new SomeType());

要调用 setter,您实际上必须为属性分配一个新集合:

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

yourClass.Textures = newTextures;

【讨论】:

  • 凹凸。这就是为什么公开 List 而不是 IEnumerable 和 AddFoo 方法通常被认为是反模式的原因。
  • @annakata 您能否在答案中详细说明如何执行此操作?
  • @annakata 我在这里添加了一个新问题stackoverflow.com/questions/4145324/…
  • @Andreas - 在您感兴趣的上下文中,您必须覆盖诸如 CollectionEditor.EditValue 方法之类的东西,但我更笼统地说,您希望将 List 实现封装在 gettable 后面IEnumerable (或 ICollection 可能)和 AddFoo(T foo) 方法(和/或其他 CRUD 操作)。这可以保护实施的完整性,让您获得成功。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-22
  • 2010-11-25
  • 2012-07-23
  • 2019-06-22
  • 2012-03-07
相关资源
最近更新 更多