Trigger Filter on CollectionViewSource

前端 未结 6 1067
庸人自扰
庸人自扰 2020-12-04 08:27

I am working on a WPF desktop application using the MVVM pattern.

I am trying to filter some items out of a ListView based on the text typed in a

6条回答
  •  再見小時候
    2020-12-04 09:09

    I just discovered a much more elegant solution to this issue. Instead of creating a ICollectionView in your ViewModel (as the accepted answer suggests) and setting your binding to

    ItemsSource={Binding Path=YourCollectionViewSourceProperty}
    

    The better way is to create a CollectionViewSource property in your ViewModel. Then bind your ItemsSource as follows

    ItemsSource={Binding Path=YourCollectionViewSourceProperty.View}    
    

    Notice the addition of .View This way the ItemsSource binding is still notified whenever there is a change to the CollectionViewSource and you never have to manually call Refresh() on the ICollectionView

    Note: I can't determine why this is the case. If you bind directly to a CollectionViewSource property the binding fails. However, if you define a CollectionViewSource in your Resources element of a XAML file and you bind directly to the resource key, the binding works fine. The only thing I can guess is that when you do it completely in XAML it knows you really want to bind to the CollectionViewSource.View value and binds it for you acourdingly behind the scenes (how helpful! :/) .

提交回复
热议问题