title: Filter WPF TreeView using MVVM
body: <p>I currently have a TreeView which has the following structure:</p>
  
  <pre><code>        &lt;TreeView ItemsSource="{Binding RootViewModels}"
                    FontSize="12"&gt;
              &lt;TreeView.ItemContainerStyle&gt;
                  &lt;Style TargetType="{x:Type TreeViewItem}"&gt;
                      &lt;Setter Property="local:TreeViewItemBehaviour.IsBroughtIntoViewWhenSelected"
                              Value="True" /&gt;
                      &lt;Setter Property="IsExpanded"
                              Value="{Binding IsExpanded, Mode=TwoWay}" /&gt;
                      &lt;Setter Property="IsSelected"
                              Value="{Binding IsSelected, Mode=TwoWay}" /&gt;
                      &lt;Setter Property="Visibility"
                              Value="{Binding IsVisible, Mode=TwoWay, Converter={StaticResource boolVisibilityConverter}}" /&gt;
                  &lt;/Style&gt;
              &lt;/TreeView.ItemContainerStyle&gt;
              &lt;TreeView.ItemTemplate&gt;
                  &lt;HierarchicalDataTemplate ItemsSource="{Binding Children}"&gt;
                      &lt;TextBlock Text="{Binding SomeDisplayText}" /&gt;
                  &lt;/HierarchicalDataTemplate&gt;
              &lt;/TreeView.ItemTemplate&gt;
          &lt;/TreeView&gt;
  </code></pre>
  
  <p>where <code>RootViewModels</code> and <code>Children</code> are of type <code>ObservableCollection&lt;SomeItemViewModel&gt;</code></p>
  
  <p>In the same View I have a <code>ComboBox</code> and I want the selected item in this <code>ComboBox</code> to serve as the criteria to filter the <code>TreeView</code> by. I have a ViewModelRepository which is also of type <code>ObservableCollection&lt;SomeItemViewModel&gt;</code> and is provided by my IoC container. I use this to create my other ObservableCollections that are in the XAML above.</p>
  
  <p>At the moment, I'm trying to set the <code>Visibility</code> of each SomeItemViewModel in my ViewModelRepository when an item in the ComboBox is selected. This seems to work for anything below the first two levels in the tree, but not for the 2nd level itself (the first level being the root which is always visible).</p>
  
  <p>However, it doesn't work consistently. When I apply the "filter" the correct nodes are set invisible, but if I then expand a node which contains "filtered" nodes then any subsequent "filters" fail.</p>
  
  <p>I've read about binding ItemsControls to a CollectionViewSource in order to do filtering, but I can't find an example of it's usage with the TreeView. Does anyone have any pointers on how I can use it here?</p>