Multiple Views of Observable Collection

强颜欢笑 提交于 2019-12-10 09:23:49

问题


I've been working on this problem for a while and I'm clearly missing something...

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

    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

Which is fine. I now need a second listbox containing a filtered version of the collection. The filter function pulls out the elements with a 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 the filter effects the contents of both listboxes. I guess I need a specific instance of the collection to apply the filter too or something but I'm at a loss!

Thanks for any help.


回答1:


I think the problem is that you're binding to the default view, and when you change this, you're changing the view for everything bound to the same collection. From the docs for CollectionViewSource.GetDefaultView:

All collections have a default CollectionView. WPF always binds to a view rather than a collection. If you bind directly to a collection, WPF actually binds to the default view for that collection. This default view is shared by all bindings to the collection, which causes all direct bindings to the collection to share the sort, filter, group, and current item characteristics of the one default view.

The design pattern for Collection and CollectionView is that you have one collection, but multiple views. So I think what you need to do is to make two different collection view objects on it:

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


来源:https://stackoverflow.com/questions/9686272/multiple-views-of-observable-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!