Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
671 views
in Technique[技术] by (71.8m points)

c# - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...