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

问题描述 投票:0回答:1

我有一个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,我可以修改(添加,编辑,删除)我的类别ObservableCollection,但是当我实现CategoriesView进行过滤时,我在尝试向ObservableCollection添加新类别时会收到NotSupportedException:

这种类型的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);

我已经去了Debug - > Windows - > Threads这个方法确实在主线程中

c# wpf observablecollection
1个回答
1
投票

这好像是

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

正在非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));
        });

我在另一篇文章中找到了类似的案例,你可以参考它: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

© www.soinside.com 2019 - 2024. All rights reserved.