javirs
javirs

Reputation: 1100

Filtering Multiple CollectionViews of the same ObservableCollection - WPF

I have a shopping list app. My Items have some properties like string Name, bool InList. And they implement the INotifyPropertyChanged thing. It works so far.

I get the items from a server and store them in a ObservableCollection<Item> AllItemsInDataBase.

In the user interface I have

  1. A List with all Items (for debug purposes)
  2. A List with the items already in the shopping List (item.InList == true)
  3. A TextBox where users can type names and they "are offered" with items with similar name.

For the full list I simply create a ListBox and attached the ItemsSource to AllItemsInDataBase it works like a charm. They appear as they load in and everything's cool

Now for the two other lists (items in the shopping list, and items matching the search word) I created a ListCollectionView, attached it to the main list and added a Filter. Like that:

public ListCollectionView ItemsInList;
ItemsInList = CollectionViewSource.GetDefaultView(AllItemsInDataBase) as ListCollectionView;
ItemsInList.Filter = i =>  (i as Item).InList ;

//fill sources for ListBox in the UI
shoppingListLB.ItemsSource = ItemsInList;
allItemsLB.ItemsSource = AllItemsInDataBase;   

And my problem is that BOTH list get filtered!

How do you create different simultaneous views for the same collection and display them at the same time ??

PS: Once it is working I will create another view with the Items matching the search box, so I need three concurrent filters

Upvotes: 2

Views: 911

Answers (1)

mm8
mm8

Reputation: 169200

Whenever you try to bind to an ObservableCollection<T>, you are actually always binding to an automatically generated view and not to the actual source collection itself. All collections have a default view which is shared by all bindings to the collection. That's why both controls are filtered.

You could solve this by creating a ListCollectionView and bind to this one instead of the ObservableCollection<Item>:

Items = new ListCollectionView(AllItemsInDataBase);

Upvotes: 1

Related Questions