我有一个MainViewModel和一个CategoryViewModel
MainViewmodel有集合:
public ObservableCollection<Category> Categories { get; set; }
Inside CategoryModel我有ICollectionView用于过滤:
public ICollectionView CategoriesView { get; set; }
CategoriesView = CollectionViewSource.GetDefaultView(_mainViewModel.Categories );
CategoriesView .Filter = new Predicate<object>(o => Filter(o as Category));
问题是,如果我不使用CategoriesView,我可以修改(添加,编辑,删除)我的类别ObservableCollection,但是当我实现CategoriesView进行过滤时,我在尝试添加新类别时会得到NotSupportedException的ObservableCollection:
此类型的CollectionView不支持从与Dispatcher线程不同的线程更改其SourceCollection
了App.Current.Dispatcher.Invoke((Action)delegate
{
_mainViewModel.Categories.Add(newCategory);
});
此外:
BindingOperations.EnableCollectionSynchronization(_matchObsCollection , _lock);
我已经去过Debug - &gt; Windows - &gt;主题 该方法确实在主线程
中答案 0 :(得分: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