title: WPF DataGrid Sorting - Data is visually sorted. Underlying data is not sorted
body: <p>Would someone be able to provide some guidance to this problem:</p>
  
  <p>I have a DataGrid which is bound to a DataTable.</p>
  
  <p>Relevant XAML &amp; code:</p>
  
  <pre><code>&lt;DataGrid Name="dataGrid1" IsReadOnly="True" ItemsSource="{Binding}" 
  &lt;DataGrid.Columns&gt;
  &lt;DataGridTextColumn Header="Name" Binding="{Binding Path=Name}" /&gt;
  &lt;DataGridTextColumn Header="Path" Binding="{Binding Path=Path}" /&gt;
  &lt;/DataGrid.Columns&gt;
  
  
  dataGrid1.DataContext = gridData.dt; // this is a DataTable with 3 columns.
  </code></pre>
  
  <p>The 3rd dt column is not shown on the grid. It's used as the id.</p>
  
  <p>The data table is sorted on the first column and contents are displayed.
  The user can sort on either of Name or Path columns/headings by clicking on them and visually sorting is/displays fine. The problem is when I examine the grid's data by selecting a particular row, the DataTable's data remains unsorted.</p>
  
  <p>My question, what is the best approach to update the grid's underlying data upon a user sorting on one of the columns? (This requires sorting the DataTable on the proper column)</p>
  
  <p>This is what I have observed:</p>
  
  <ol>
  <li>Adding a Click event handler on DataGridColumnHeader does fire the event. 
  I have observed that the value of columnHeader.SortDirection (in sender) is the 
  CURRENT value, not the target value. Is it correct to say that a given column
  sort order goes through these phases:
  null --> ascending
  descending --> ascending
  ascending to descending</li>
  </ol>
  
  <p>I.E. By knowing the current state, the next state is determinable. </p>
  
  <ol>
  <li>I can place a trigger in the DataGridColumnHeader's SortDirection property looking for Ascending/Descending/null but then what? Can I execute code against this?
  If so, can you show me a code fragment.</li>
  </ol>
  
  <p>I have gone through similar posts and tried to perform the following:</p>
  
  <ul>
  <li><p>experimented with a CollectionViewSource by binding my DataGrid to one. As an experiment, I trapped the column header click event and forced a sorting order on the columns. This did not work. (My implementation may be wrong?)</p></li>
  <li><p>I added SortedMemberPath= "xx" to my XAML to the specific DataGridTextColumn entries. </p></li>
  </ul>
  
  <p>Any assistance greatly appreciated.</p>