title: MVVM Dynamic DataGrid Sorting Filtering
body: <p>I have a <code>DataGrid</code> that gets its data updated every few seconds via a <code>Thread</code>. The <code>DataGrid</code> needs to offer Column Header sorting, grouping and filtering.</p>
  
  <p>I currently have a <code>DataGrid</code> bound to a <code>ICollectionView</code> and the source of the <code>ICollectionView</code> is an <code>ObservableCollection</code>. Which seems to be the good way to do it from what I read on other threads.</p>
  
  <p>The sort-ing "works" but it gets lost when the <code>ICollectionView.Source</code> gets updated following an update of the <code>ObservableCollection</code>. I have tried saving the <code>SortDescriptions</code> before the update and re-add it to the <code>ICollectionView</code> after the update is done. But it's the same result.</p>
  
  <p>May someone point me to what I'm missing?</p>
  
  <p><strong>Edit Here's some code...</strong>  </p>
  
  <p>View (XAML)  </p>
  
  <pre><code>&lt;DataGrid ItemsSource="{Binding CollectionView, Source={StaticResource ViewModel}}&gt;
  </code></pre>
  
  <p>ViewModel</p>
  
  <pre><code>public ICollectionView CollectionView
  {
      get
      {
          collectionViewSource.Source = dataColl;
          if (SortDescriptions != null)
          {
              foreach (SortDescription sd in SortDescriptions)
              {
                  collectionViewSource.View.SortDescriptions.Add(sd);
              }
          }
          collectionViewSource.View.Refresh();
          return collectionViewSource.View;
      }
  }
  
  public ObservableCollection&lt;SomeObject&gt; DataColl
  {
      get { return dataColl; }
      private set 
      {
          this.dataColl= value;
          OnPropertyChanged("CollectionView");
      }
  }
  </code></pre>
  
  <p>Following is the method that updates the data every few seconds...  </p>
  
  <pre><code>private void UpdateData()
  {
      while (true)
      {
          System.Threading.Thread.Sleep(mDataRefreshRate);
  
          // SortDescriptions is a Property of the ViewModel class.
          SortDescriptions = collectionViewSource.View.SortDescriptions;
  
          ObservableCollection&lt;SomeObject&gt; wDataColl
             = new ObservableCollection&lt;SomeObject&gt;();
  
          //... Irrelevant code that puts the data in wDataColl ...
  
          DataColl= wDataColl;
      }
  }
  </code></pre>