wpfmvvmcollectionviewsource

CollectionViewSource filtering only in xaml


My textbox provides the filtered string to the collection and when I enter new value in the textbox, I want my collection to be refreshed as per the new filter value. I want to put the filtering logic not in my viewmodel or code behind but only in XAML. The code is attached below. The sorting and grouping are working fine. I have checked this answer: https://stackoverflow.com/a/6462282/5130106, it is almost doing the stuff but lacks when it comes to refreshing the collection, therefore, I am creating a new question, as I cannot find an answer.

Is there a way I could achieve this?

   <TreeView x:Name="SystemsTreeView" ItemsSource="{Binding Source={StaticResource SystemCollection}, Path=Groups}">

     <CollectionViewSource x:Key="SystemCollection" Source="{Binding SystemsList}" Filter="{MyLogic}">   
        <!--Sorting of Systems--> 
        <CollectionViewSource.SortDescriptions>
            <scm:SortDescription PropertyName="SystemName"/>
            <scm:SortDescription PropertyName="Version" Direction="Descending"/>
        </CollectionViewSource.SortDescriptions>
         <!--Grouping of Systems--> 
        <CollectionViewSource.GroupDescriptions>
            <PropertyGroupDescription PropertyName="SystemName" />
        </CollectionViewSource.GroupDescriptions>                
    </CollectionViewSource>

Solution

  • I want to put the filtering logic not in my viewmodel or code behind but only in XAML

    Not possible. You can't do this in pure XAML. XAML is a markup language. You should implement your logic in a programming language.

    Givne your current setup, you should call Refresh() on the CollectionViewSource whenever the TextBox changes, for example in a TextChanged event handler in the code-behind.

    If you want to refresh the filter from the view model, you should perform the actual filtering there as well. You may for example expose an ICollectionView that the view binds to. It makes no sense to define the filtering logic in the view but try to refresh it from the view model.