Reputation: 63
Would someone be able to provide some guidance to this problem:
I have a DataGrid which is bound to a DataTable.
Relevant XAML & code:
<DataGrid Name="dataGrid1" IsReadOnly="True" ItemsSource="{Binding}"
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Binding="{Binding Path=Name}" />
<DataGridTextColumn Header="Path" Binding="{Binding Path=Path}" />
</DataGrid.Columns>
dataGrid1.DataContext = gridData.dt; // this is a DataTable with 3 columns.
The 3rd dt column is not shown on the grid. It's used as the id.
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.
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)
This is what I have observed:
I.E. By knowing the current state, the next state is determinable.
I have gone through similar posts and tried to perform the following:
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?)
I added SortedMemberPath= "xx" to my XAML to the specific DataGridTextColumn entries.
Any assistance greatly appreciated.
Upvotes: 1
Views: 1941
Reputation: 30820
Use DataGrid.Sorting event:
public class DataGrid : MultiSelector
{
...
//
// Summary:
// Occurs when a column is being sorted.
public event DataGridSortingEventHandler Sorting;
...
}
In event handler, use e.Column property to find out which column was used to sort data:
void dataGrid1_Sorting(object sender, DataGridSortingEventArgs e)
{
e.Column ... // TODO
}
Upvotes: 1