我有一个带有可排序列的WPF DataGrid。我不想预先排序任何特定列上的网格。当用户第一次单击列标题时,我只想要默认的排序方向是下行而不是升序。
在更改排序列时,SortDescription.Direction上的CollectionViewSource和by DataGridTextColumns的SortDirection属性都不会影响默认排序方向。它总是在列标题的第一次单击时选择升序。
99%的时间它需要下降和切换列在用户工作流中是频繁的,因此这是增加了许多不必要的点击。如果有XAML解决方案,我会非常喜欢,但如果有必要,我会在事件上使用代码欺骗。
发布于 2016-05-20 21:52:35
似乎在不对排序处理程序进行小干预的情况下,您无法做到这一点,因为DataGrid所做的默认排序是这样启动的:
ListSortDirection direction = ListSortDirection.Ascending;
ListSortDirection? sortDirection = column.SortDirection;
if (sortDirection.HasValue && sortDirection.Value == ListSortDirection.Ascending)
direction = ListSortDirection.Descending;
因此,只有在列被排序之前,并且这类列是上升的情况下,它才会将其翻转到降序。然而,通过微小的黑客,你可以实现你想要的。首先订阅DataGrid.Sorting事件,然后在那里:
private void OnSorting(object sender, DataGridSortingEventArgs e) {
if (e.Column.SortDirection == null)
e.Column.SortDirection = ListSortDirection.Ascending;
e.Handled = false;
}
因此,基本上,如果还没有排序--您可以将其切换到Ascending
,并将其传递给DataGrid
的默认排序(通过将e.Handled
设置为false
)。在排序开始时,它会为您将其切换到Descending
,这就是您想要的。
您可以在xaml中使用附加属性来完成这一任务,如下所示:
public static class DataGridExtensions {
public static readonly DependencyProperty SortDescProperty = DependencyProperty.RegisterAttached(
"SortDesc", typeof (bool), typeof (DataGridExtensions), new PropertyMetadata(false, OnSortDescChanged));
private static void OnSortDescChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
var grid = d as DataGrid;
if (grid != null) {
grid.Sorting += (source, args) => {
if (args.Column.SortDirection == null) {
// here we check an attached property value of target column
var sortDesc = (bool) args.Column.GetValue(DataGridExtensions.SortDescProperty);
if (sortDesc) {
args.Column.SortDirection = ListSortDirection.Ascending;
}
}
};
}
}
public static void SetSortDesc(DependencyObject element, bool value) {
element.SetValue(SortDescProperty, value);
}
public static bool GetSortDesc(DependencyObject element) {
return (bool) element.GetValue(SortDescProperty);
}
}
然后在你的xaml中:
<DataGrid x:Name="dg" AutoGenerateColumns="False" ItemsSource="{Binding Items}" local:DataGridExtensions.SortDesc="True">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Value}"
Header="Value"
local:DataGridExtensions.SortDesc="True" />
</DataGrid.Columns>
</DataGrid>
因此,基本上您使用SortDesc=true
标记SortDesc=true
本身,以订阅排序事件,然后只标记需要排序的列。如果存在逻辑,还可以将SortDesc
绑定到模型。
https://stackoverflow.com/questions/37355830
复制相似问题