什么是notifycollectionchangedaction重置值

Rel*_*ity 15 wpf reset mvvm inotifycollectionchanged

我有一个可观察的集合...... SelectableDataContext<T>在泛型类SelectableDataContext<T>中......有两个私有成员变量

  1. 私人T项目.
  2. 私人布尔被选中.

当IsSelected属性发生更改时...我的集合的已更改属性未触发.

我认为它应该解雇...因为它ResetINotifyCollectionChangedAction.

G. *_*ard 37

这是一个古老的问题,但是为了任何可能通过搜索遇到这种情况的人的利益:

NotifyCollectionChangedAction.Reset意思是"收藏内容发生了巨大变化".引发Reset事件的一种情况是调用Clear()底层的observable集合.

使用Reset事件,您不会在参数中获取NewItemsOldItems集合NotifyCollectionChangedEventArgs.

这意味着您最好使用事件的"发送者"来获取对已修改集合的引用并直接使用它,即假设它是一个新列表.

这方面的一个例子可能是这样的:

((INotifyCollectionChanged)stringCollection).CollectionChanged += new NotifyCollectionChangedEventHandler(StringCollection_CollectionChanged);
  ...

void StringCollection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
    switch (e.Action)
    {
        case NotifyCollectionChangedAction.Add:
            foreach (string s in e.NewItems)
            {
                InternalAdd(s);
            }
            break;

        case NotifyCollectionChangedAction.Remove:
            foreach (string s in e.OldItems)
            {
                InternalRemove(s);
            }
            break;

        case NotifyCollectionChangedAction.Reset:
            ReadOnlyObservableCollection<string> col = sender as ReadOnlyObservableCollection<string>;
            InternalClearAll();
            if (col != null)
            {
                foreach (string s in col)
                {
                    InternalAdd(s);
                }
            }
            break;
    }
}
Run Code Online (Sandbox Code Playgroud)

这里有很多关于此重置事件的讨论:当清除ObservableCollection时,e.OldItems中没有项目.

  • MS更改了“重置”的定义。现在的意思是:“已清除集合的内容。” https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.specialized.notifycollectionchangedaction?view=netframework-4.7.2 (3认同)
  • 不再。它已被澄清为“发生了巨大变化”,这可能意味着清除,但也意味着每个元素都发生了变化。请参阅 https://github.com/dotnet/dotnet-api-docs/issues/3253 (2认同)

Tal*_*ner -1

当且仅当您通过添加新项目或从集合中删除现有项目来修改集合时,才会触发集合更改。