为什么 WPF 没有在 INotifyPropertyChanged 上更新
本文关键字:INotifyPropertyChanged 更新 WPF 为什么 | 更新日期: 2023-09-27 18:30:40
我通过实现相同的接口并将调用传递给ObservableCollection`1
来实现INotifyPropertyChanged
:
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
被调用,并且在更改属性时引发了事件。
将.add
调用传递给内部列表是不够的,因为 WPF 使用事件的 sender
参数来确定需要更新哪些绑定。 使用以下命令在更新sender
时包装INotifyPropertyChanged
:
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
}