Search code examples
wpfmvvmcollectionviewsource

CollectionViewSource is not triggering the filter event when refresh is called


The idea is, I have a textbox in which I type a string, this string will filter the collectionviewsource which is a treeview. Attaching the code below:

The sorting and grouping are working fine.

View.xaml

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

     <CollectionViewSource x:Key="SystemCollection" Source="{Binding SystemsList}" Filter="SystemCollectionChangeFilter" IsLiveFilteringRequested="True" >   
        <CollectionViewSource.LiveFilteringProperties>
                        <clr:String>SystemName</clr:String>
                        <clr:String>Version</clr:String>
                    </CollectionViewSource.LiveFilteringProperties>
        <!--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>

The SystemCollectionChangeFilter calls the method on the viewmodel to filter.

ViewModel

ICollectionView viewSource = CollectionViewSource.GetDefaultView(SystemsList); //in the constructor


private string _systemNameFilter;

public string SystemNameFilter //Attached to Textbox (for filtering)
{
   get { return _systemNameFilter; }
   set
   {
      if (_systemNameFilter != value)
         {
            _systemNameFilter = value;
             viewSource.Refresh();  //This is not triggering the filtering event.  
             NotifyPropertyChanged();
         }
    }
}

The viewSource.Refresh() is not triggering the filter event on the collectionviewsource. I have checked that the filtering event is only triggered when the usercontrol is loaded.

Tried so far:

  1. I have also tried by keeping LiveFilteringRequested property to true in xaml and also tried to add the CollectionViewType, but none of it is working.
  2. Trigger Filter on CollectionViewSource, this solution requires me to keep the stuff in viewmodel rather than in xaml which is a problem for me.

Would be helpful if you can recommend any mvvm based solution for the above problem.


Solution

  • Call Refresh() on the CollectionViewSource named "SystemCollection" in the view or implement an ICollectionView, or any other type of source collection, in the view model and refresh it from there.

    Adding LiveFilteringProperties should also work provided that the generated CollectionView implements the ICollectionViewLiveShaping interface.