Several types of observable collection

I have been working on this issue for a while and I obviously missed something ...

I create, populate and bind an observable collection like this:

Dim _ObservableWEI As New ObservableWEI ... _ObservableWEI.Add(New WEI() With {.WEInum = 1, .WEIvalue = 1}) _ObservableWEI.Add(New WEI() With {.WEInum = 2, .WEIvalue = 0}) _ObservableWEI.Add(New WEI() With {.WEInum = 3, .WEIvalue = 2}) ... lbxAll.ItemsSource = _ObservableWEI 

This is normal. Now I need a second list containing a filtered version of the collection. The filter function draws items using WEIvalue = 1.

  Dim view As ListCollectionView ... view = CType(CollectionViewSource.GetDefaultView(_ObservableWEI), ListCollectionView) view.Filter = New Predicate(Of Object)(AddressOf ListFilter) ... lbxView.ItemsSource = view 

The problem is that the filter affects the contents of both lists. I think I need a specific collection instance to apply the filter too or something, but I'm at a loss!

Thanks for any help.

+4
source share
1 answer

I think the problem is that you are attached to the default view, and when you change this, you change the view to everything related to the same collection. From the docs for CollectionViewSource.GetDefaultView :

All collections have a CollectionView by default. WPF always binds to a view, not a collection. If you bind directly to a collection, WPF actually binds to the default view for that collection. This view is used by default with all relations with the collection, which leads to the fact that all direct bindings of the collection combine the sorting, filtering, group and current element characteristics of the same view by default.

The design pattern for Collection and CollectionView is that you have one collection but several types. Therefore, I think you need to make two collector view objects:

 Dim view1 As new ListCollectionView(_ObservableWEI) 'set filtering, grouping, etc. 'bind to it lbxAll.ItemsSource = view1 Dim view2 As new ListCollectionView(_ObservableWEI) 'set filtering, grouping, etc. 'bind to it lbxView.ItemsSource = view2 
+3
source

Source: https://habr.com/ru/post/1401189/


All Articles