user1416072
user1416072

Reputation: 107

Adding item to ObsercableCollection with ICollectionView for filtering WPF

I have a MainViewModel and a CategoryViewModel

MainViewmodel has the collection:

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

Inside CategoryViewModel I have the ICollectionView for filtering:

    public ICollectionView CategoriesView { get; set; }

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

The thing is that if I don't use CategoriesView I can modify (add, edit, remove) my Categories ObservableCollection, but when I implement the CategoriesView for filtering, I get a NotSupportedException when trying to add a new Category to the ObservableCollection:

This type of CollectionView does not support changes to its SourceCollection from a thread different from the Dispatcher thread

I already tried 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);
            });

Also:

BindingOperations.EnableCollectionSynchronization(_matchObsCollection , _lock);

I already went to Debug --> Windows --> Threads The method is indeed in the Main Thread

Upvotes: 0

Views: 1177

Answers (1)

pengMiao
pengMiao

Reputation: 344

It seems like

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

is running on a non-ui thread. Try to run it by Dispatcher.Invoke to ensure it run on main-ui thread :

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

I found a similar case in another post you may refer to it : 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

Upvotes: 1

Related Questions