Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Datagrid : Is there no Sorted event?

I need to know when a WPF Datagrid has been sorted by the user. Why is there no Sorted event? I can only find a Sorting event.

I also investigated the CollectionView and ListCollectionView that is exposing the objects to the View, without any luck.

I am quite surprised as this should come out of the box. Any ideas?

like image 836
Houman Avatar asked Mar 05 '12 17:03

Houman


1 Answers

I've taken an example from MSDN documentation and adjusted it to raise a Sorted event when the Sorting event is done.

public class CustomDataGrid : DataGrid
{
    // Create a custom routed event by first registering a RoutedEventID
    // This event uses the bubbling routing strategy
    public static readonly RoutedEvent SortedEvent = EventManager.RegisterRoutedEvent(
        "Sorted", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(CustomDataGrid));
    
    // Provide CLR accessors for the event
    public event RoutedEventHandler Sorted
    {
        add { AddHandler(SortedEvent, value); }
        remove { RemoveHandler(SortedEvent, value); }
    }

    // This method raises the Sorted event
    void RaiseSortedEvent()
    {
        RoutedEventArgs newEventArgs = new RoutedEventArgs(CustomDataGrid.SortedEvent);
        RaiseEvent(newEventArgs);
    }

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

Then you can use it either in codebehind.

datagrid.Sorted += new RoutedEventHandler(datagrid_Sorted);

or in XAML

<local:CustomDataGrid x:Name="datagrid" Sorted="datagrid_Sorted"/>

And here the method that will get triggered when the datagrid finishing sorting:

private void datagrid_Sorted(object sender, RoutedEventArgs args)
{
     var datagrid = (CustomDataGrid)sender;
     var sortedItems = datagrid.Items;

}
like image 85
Carol Avatar answered Oct 04 '22 16:10

Carol