2

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

Eliahu Aaron
  • 4,103
  • 5
  • 27
  • 37
javirs
  • 1,049
  • 26
  • 52
  • See: [Multiple ItemsControl on single collection applies filter to all views at once](https://stackoverflow.com/questions/38542781/multiple-itemscontrol-on-single-collection-applies-filter-to-all-views-at-once) – Eliahu Aaron Jun 04 '20 at 10:55

1 Answers1

1

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);
mm8
  • 163,881
  • 10
  • 57
  • 88
  • Perfect!! I created the Items as you did, and set the ItemsSource to the Items, instead of the original AllItemsInDataBase. Now no ListBox connects straight to the ObservableCollection. They all point to ListCollectionView, and it works ! :) – javirs Jul 04 '19 at 13:26