我需要知道用户何时对 WPF Datagrid 进行了排序。为什么没有Sorted
事件?我只能找到一个排序事件。
我还调查了将对象暴露给View的CollectionView
和ListCollectionView
,没有任何运气。
我很惊讶,因为这应该是开箱即用的。 有什么想法吗?
答案 0 :(得分:3)
我已经从MSDN documentation采取了一个示例,并在排序事件完成时调整它以引发Sorted事件。
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();
}
}
然后你可以在代码隐藏中使用它。
datagrid.Sorted += new RoutedEventHandler(datagrid_Sorted);
或在XAML中
<local:CustomDataGrid x:Name="datagrid" Sorted="datagrid_Sorted;"/>
答案 1 :(得分:2)
datagrid有“排序”事件,订阅它!
XAML:
<DataGrid ItemsSource="{Binding YourItems}" AutoGenerateColumns="True" anUserSortColumns="True"
Sorting="DataGrid_Sorting"/>
.cs代码:
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 :(得分:0)
您仍然可以订阅DataGrid排序事件:
<local:CustomDataGrid x:Name="datagrid" Sorting="datagrid_Sorted;"/>
但是要确保您的操作在排序完成后发生,请使用Dispatcher:
private void DataGrid_Sorting(object sender, DataGridSortingEventArgs e)
{
this.Dispatcher.BeginInvoke((Action)delegate()
{
//runs after sorting is done
}, null);
}
这样,就不需要自定义Datagrid类。