Datagrid : Is there no Sorted event?

妖精的绣舞 提交于 2020-01-13 09:04:25

问题


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?


回答1:


datagrid has "Sorting" event, subscribe to it!

XAML:

<DataGrid ItemsSource="{Binding YourItems}" AutoGenerateColumns="True" anUserSortColumns="True" 
           Sorting="DataGrid_Sorting"/>

.cs code:

private void DataGrid_Sorting(object sender, System.Windows.Controls.DataGridSortingEventArgs e)
{
    Console.WriteLine(string.Format("sorting grid by '{0}' column in {1} order", e.Column.SortMemberPath, e.Column.SortDirection));
}



回答2:


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;"/>



回答3:


You can still subscribe to the DataGrid Sorting Event:

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

but to make sure that your actions happen after the sorting is done use Dispatcher :

private void DataGrid_Sorting(object sender, DataGridSortingEventArgs e)
{

    this.Dispatcher.BeginInvoke((Action)delegate()
    {
        //runs after sorting is done
    }, null);
}

This way, there's no need of a custom Datagrid class.



来源:https://stackoverflow.com/questions/9571178/datagrid-is-there-no-sorted-event

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!