【发布时间】:2011-06-06 16:56:26
【问题描述】:
在专门从事 ASP.Net 工作几年后,我刚刚开始接触 WPF。我目前正在努力解决的问题是我有一个需要绑定到列表框的自定义集合类。一切似乎都在工作,除了从集合中删除一个项目。当我尝试时,我得到了错误:“Collection Remove event must specify item position.” 问题是这个集合不使用索引,所以我没有看到指定位置的方法,到目前为止谷歌未能向我展示一个可行的解决方案......
该类被定义为实现ICollection<> 和INotifyCollectionChanged。我的内部项目容器是一个Dictionary,它使用项目的名称(字符串)值作为键。除了这两个接口定义的方法之外,该集合还有一个索引器,允许通过名称访问项目,并覆盖 Contains 和 Remove 方法,以便也可以使用项目名称调用它们。这适用于添加和编辑,但当我尝试删除时会引发上述异常。
以下是相关代码的摘录:
class Foo
{
public string Name
{
get;
set;
}
}
class FooCollection : ICollection<Foo>, INotifyCollectionChanged
{
Dictionary<string, Foo> Items;
public FooCollection()
{
Items = new Dictionary<string, Foo>();
}
#region ICollection<Foo> Members
//***REMOVED FOR BREVITY***
public bool Remove(Foo item)
{
return this.Remove(item.Name);
}
public bool Remove(string name)
{
bool Value = this.Contains(name);
if (Value)
{
NotifyCollectionChangedEventArgs E = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, Items[name]);
Value = Items.Remove(name);
if (Value)
{
RaiseCollectionChanged(E);
}
}
return Value;
}
#endregion
#region INotifyCollectionChanged Members
public event NotifyCollectionChangedEventHandler CollectionChanged;
private void RaiseCollectionChanged(NotifyCollectionChangedEventArgs e)
{
if (CollectionChanged != null)
{
CollectionChanged(this, e);
}
}
#endregion
}
【问题讨论】:
-
您是否尝试过始终给出 -1 的位置?
-
根据调试默认为-1。我发现其他人收到类似错误的一些帖子指出该位置必须是 int >= 0 和
-
由于这个确切的问题,我可以告诉你,我们小组在 ObservableDictionary 上的尝试是“非法的”,而是使用派生的 ObservableCollection 添加确保唯一性所需的业务逻辑(通过某些属性/功能) .
-
您是否尝试过使用 .ToList()(在 LINQ 中)将字典转换为列表并以这种方式获取索引?
-
@Camron - 我想到了按照这些思路做一些事情,并且可能会奏效,但我希望有一些更优雅/高效的东西。