title: how to bind datagrid to collectionviewsource using xaml
body: <p>I have a datagrid which is bound to a collectionviewsource, which is bound to an observablecollection.  In following a guide I've set it up like so: </p>
  
  <p>My Persons class:</p>
  
  <pre><code>public class Persons : ObservableCollection&lt;Person&gt;
  {
      //...
  }
  </code></pre>
  
  <p>The xaml data bindings:</p>
  
  <pre><code>&lt;Window.Resources&gt;
      &lt;local:Persons x:Key="_Persons"/&gt;
      &lt;CollectionViewSource x:Key="cvsPersons" Source="{StaticResource _Persons}" /&gt;                       
  &lt;/Window.Resources&gt;
  </code></pre>
  
  <p>The datagrid binding:</p>
  
  <pre><code> &lt;DataGrid x:Name="myDataGrid" ItemsSource="{Binding Source={StaticResource cvsPersons}}"/&gt;
  </code></pre>
  
  <p>The code behind:</p>
  
  <pre><code>_Persons = (Persons)this.Resources["_Persons"];
  _persons = //some method to fill perons;
  cvsPersons = (CollectionViewSource)this.Resources["cvsPersons"];             
  cvsPersons.Source = _Persons;
  </code></pre>
  
  <p>The above works.  <strong>My question is, why do I need to set the collectionviewsource.source in code behind using cvsPersons.Source = _Persons;?  I thought the xaml in my very first snippet did this job:</strong></p>
  
  <pre><code>_cvsPersons.Source = _Persons;  
  </code></pre>
  
  <p>If I need all this code behind then the xaml databinding code seems of little benefit, I may as well do everything in code behind.  From my (perhaps little) understanding, the only code needed in code behind would be to reference the instances setup by xaml, ie:</p>
  
  <pre><code>_Persons = (Persons)this.Resources["_Persons"];
  _persons = //some method to fill perons;
  cvsPersons = (CollectionViewSource)this.Resources["cvsPersons"];
  </code></pre>
  
  <p>If I don't have  _cvsPersons.Source = _Persons; then my datagrid does not get populated.  My xaml as it stands doesn't do the job.  I guess my question is more concept related..</p>