我是一个长期专攻ASP.Net的开发者,现在刚开始涉足WPF。我目前遇到的问题是,我有一个需要绑定到listbox的自定义集合类。除了删除一个项目以外,一切都运作良好。当我尝试删除一个项目时,出现错误:"Collection Remove event must specify item position."
。问题在于这个集合不使用索引,所以我找不到指定位置的方法,到目前为止谷歌也没能给我提供可行的解决方案。
这个类定义了实现ICollection<>
和INotifyCollectionChanged
接口。我的内部项目容器是一个Dictionary
,它使用项的名称(string)值作为键。除了这两个接口定义的方法之外,这个集合还有一个索引器,可以通过名称访问项目,并重写了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
}