Angelo Carzis
Angelo Carzis

Reputation: 63

WPF DataGrid Sorting - Data is visually sorted. Underlying data is not sorted

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:

  1. 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

I.E. By knowing the current state, the next state is determinable.

  1. 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.

I have gone through similar posts and tried to perform the following:

Any assistance greatly appreciated.

Upvotes: 1

Views: 1941

Answers (1)

decyclone
decyclone

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

Related Questions