title: Implementing a ListView Filter with Josh Smith's WPF MVVM Demo App
body: <p>I've been trying to expand Josh Smith's demo MVVM application in order to better understand the principals behind it and I've hit a wall when trying to implement a filter function on a View using a ListView.</p>
  
  <p>I have spent a few hours researching and dabbling but its just not working.</p>
  
  <p>My first step was to bind a textbox in my view to a property in my ViewModel:</p>
  
  <pre><code>&lt;TextBox Height="25" Name="txtFilter" Width="150" Text="{Binding Path=Filter, UpdateSourceTrigger=PropertyChanged}"/&gt;
  </code></pre>
  
  <p>This matches in my VM:</p>
  
  <pre><code>public string Filter
      {
          get { return this.filter; }
          set
          {
              this.filter = value;
              OnFilterChanged();
          }
      }
  </code></pre>
  
  <p>My VM used a ObservableCollection for the datasource but I've tried to convert it into an ICollectionView after reading tutorials:</p>
  
  <pre><code>internal ObservableCollection&lt;StaffViewModel&gt; InnerStaff { get; set; }
      internal CollectionViewSource CvsStaff { get; set; }
      public ICollectionView AllStaff
      {
          get { return CvsStaff.View; }
      }
  </code></pre>
  
  <p>In my constructor I have specified:</p>
  
  <pre><code>CvsStaff = new CollectionViewSource();
  CvsStaff.Source = this.InnerStaff;
  CvsStaff.Filter += ApplyFilter;
  </code></pre>
  
  <p>When my Filter Property gets updated it calls OnFilterChanged which is:</p>
  
  <pre><code>private void OnFilterChanged()
      {
          CvsStaff.View.Refresh();
      }
  </code></pre>
  
  <p>My ApplyFilter Function is:</p>
  
  <pre><code>void ApplyFilter(object sender, FilterEventArgs e)
      {
          StaffViewModel svm = (StaffViewModel)e.Item;
  
          if (this.Filter.Length == 0)
          {
              e.Accepted = true;
          }
          else
          {
              e.Accepted = svm.LastName.Contains(Filter);
          }
      }
  </code></pre>
  
  <p>Is there a silly mistake that I've made that anyone can help me spot? I'm fairly new to WPF and the MVVM pattern so I'm still learning!</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>In the View I bind the collection with:</p>
  
  <pre><code>&lt;CollectionViewSource
    x:Key="StaffGroup"
    Source="{Binding Path=AllStaff}"
    /&gt;
  </code></pre>
  
  <p>and the ListView is as such:</p>
  
  <pre><code>&lt;ListView
        Name="staffList"
        AlternationCount="2" 
        DataContext="{StaticResource StaffGroup}" 
        ItemContainerStyle="{StaticResource StaffItemStyle}"
        ItemsSource="{Binding}"
          Grid.Row="1"&gt;
  </code></pre>