在ASP.Net专门工作了几年之后,我刚刚在WPF中弄湿了脚趾。我目前正在努力解决的问题是我有一个自定义集合类,我需要绑定到列表框。除了从集合中删除项目之外,一切似乎都在起作用。当我试图得到错误时: “Collection Remove event must specify item position.”
问题是这个集合没有使用索引,所以我没有看到指定位置的方法,到目前为止谷歌没有向我展示一个可行的解决方案......
该类被定义为实现 ICollection<>
和 INotifyCollectionChanged
。我的内部物品容器是 Dictionary
它使用项目的名称(字符串)值作为键。除了这两个接口定义的方法之外,此集合还有一个索引器,允许通过Name访问项目,并覆盖 Contains
和 Remove
方法,以便也可以使用项目Name调用它们。这适用于添加和编辑,但在我尝试删除时会抛出上述异常。
以下是相关代码的摘录:
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
}