为什么WPF不能在INotifyPropertyChanged上更新?

时间:2016-01-16 05:54:36

标签: c# wpf

我通过实现相同的接口并将调用传递给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,并且在更改属性时会引发事件。

1 个答案:

答案 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
}