使用 ICollectionView 将项目添加到 ObsercableCollection 以过滤 WPF

Adding item to ObsercableCollection with ICollectionView for filtering WPF

我有一个 MainViewModel 和一个 CategoryViewModel

MainViewmodel 有集合:

 public ObservableCollection<Category> Categories { get; set; }

在 CategoryViewModel 中,我有用于过滤的 ICollectionView:

    public ICollectionView CategoriesView { get; set; }

CategoriesView = CollectionViewSource.GetDefaultView(_mainViewModel.Categories );
                CategoriesView .Filter = new Predicate<object>(o => Filter(o as Category));

问题是,如果我不使用 CategoriesView,我可以修改(添加、编辑、删除)我的 Categories ObservableCollection,但是当我实现 CategoriesView 进行过滤时,我在尝试添加新类别时得到 NotSupportedException到 ObservableCollection:

这种类型的 CollectionView 不支持从与 Dispatcher 线程不同的线程更改其 SourceCollection

我已经试过了This type of CollectionView does not support changes to its SourceCollection from a thread different from the Dispatcher thread

App.Current.Dispatcher.Invoke((Action)delegate
            {
                _mainViewModel.Categories.Add(newCategory);
            });

还有:

BindingOperations.EnableCollectionSynchronization(_matchObsCollection , _lock);

我已经转到调试 --> Windows --> 线程 方法确实在Main Thread

好像

CategoriesView = CollectionViewSource.GetDefaultView(_mainViewModel.Categories );
            CategoriesView .Filter = new Predicate<object>(o => Filter(o as Category));

运行正在 non-ui 线程上。尝试通过 Dispatcher.Invoke 运行 以确保它 运行 在 main-ui 线程上:

App.Current.Dispatcher.Invoke((Action)delegate
        {
            CategoriesView = CollectionViewSource.GetDefaultView(_mainViewModel.Categories );
            CategoriesView .Filter = new Predicate<object>(o => Filter(o as Category));
        });

我在另一个 post 中发现了类似的案例,您可以参考它:https://social.msdn.microsoft.com/Forums/vstudio/en-US/ba22092e-ddb5-4cf9-95e3-8ecd61b0468d/listview-not-updating-white-copying-files-in-different-thread?forum=wpf