我通过实现相同的接口并将调用传递给INotifyPropertyChanged
来实现ObservableCollection`1
:
class WrappedObservableCollection<TElement> : INotifyPropertyChanged, INotifyCollectionChanged //, ...others
{
private readonly ObservableCollection<TElement> BaseList;
public WrappedObservableCollection(ObservableCollection<TElement> baseList)
{
Contract.Requires(baseList != null);
this.BaseList = baseList;
}
#region wrapping of BaseList
public event PropertyChangedEventHandler PropertyChanged
{
add { ((INotifyPropertyChanged)BaseList).PropertyChanged += value; }
remove { ((INotifyPropertyChanged)BaseList).PropertyChanged -= value; }
}
#endregion
}
这一切都很好,但是当我绑定到.Count
属性时,UI永远不会更新。我怀疑我的INotifyPropertyChanged
实现有问题,但我已经确认调用PropertyChanged.add
,并且在更改属性时会引发事件。
答案 0 :(得分:0)
将.add
调用传递给内部列表是不够的,因为WPF使用事件的sender
参数来确定需要更新哪些绑定。更新INotifyPropertyChanged
时使用以下内容包裹sender
:
class WrappedObservableCollection<TElement> : INotifyPropertyChanged, INotifyCollectionChanged //, ...others
{
private readonly ObservableCollection<TElement> BaseList;
public WrappedObservableCollection(ObservableCollection<TElement> baseList)
{
Contract.Requires(baseList != null);
this.BaseList = baseList;
((INotifyPropertyChanged)this.BaseList).PropertyChanged += (sender, e) => PropertyChanged?.Invoke(this, e);
}
#region wrapping of BaseList
public event PropertyChangedEventHandler PropertyChanged;
#endregion
}