Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I be notified if a DataGrid column is sorted (and not sorting)

I need to have kind of an Sorted event for a DataGrid in a WPF application but cannot find a way to get it.

Here is what I tried:

The DataGrid provides an event Sorting, but I cannot use it as it is fired before the sorting is done. The EventArgs give me the column which is sorted but not the way it is sorted and if I get the sort direction it is set to the old value. Of course I could guess what it will be as I know that it flips from none to ascending and finally to descending but that would be no solution as it would fail if the behavior of the control changes.

Second try:

The DataGrid has a default view which provides access to a SortDescriptionCollection. This collection holds all sorting properties but I don't see any possibility to let me inform about changes.

I have to say that I'm looking for a solution as clean as possible as it will be used in a large project on which I can't use solutions which could fail if the environment changes.

Does anyone know from experience (or documentation?) how I could solve this problem?

Edit: To make more clear what I want to achieve: I need to get informed which DataGrid column is sorted in which direction when a user sort a column. It is not necessary that this information comes after the sorting itself, it just has to be correct ;)

like image 239
MatthiasG Avatar asked Dec 07 '11 14:12

MatthiasG


1 Answers

I implemented the Sorted for the DataGrid event myself by overriding the DataGrid as follows:

public class ValueEventArgs<T> : EventArgs
{
    public ValueEventArgs(T value)
    {
        Value = value;
    }

    public T Value { get; set; }

}

public class DataGridExt : DataGrid
{
    public event EventHandler<ValueEventArgs<DataGridColumn>> Sorted;

    protected override void OnSorting(DataGridSortingEventArgs eventArgs)
    {
        base.OnSorting(eventArgs);

        if (Sorted == null) return;
        var column = eventArgs.Column;
        Sorted(this, new ValueEventArgs<DataGridColumn>(column));
    }
}

In order to use it then all you need to do is this:

    private void Initialize()
    {
            myGrid.Sorted += OnSorted;
    }
    private void OnSorted(object sender, ValueEventArgs<DataGridColumn> valueEventArgs)
    {
    // Persist Sort...
    }
like image 59
Stephen Lautier Avatar answered Oct 26 '22 14:10

Stephen Lautier