如何在WPF中强制DataGrid组顺序? [英] How to force DataGrid group order in WPF?

查看:80
本文介绍了如何在WPF中强制DataGrid组顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的代码:

StatusItems = new ObservableCollection<StatusItem> { };
StatusItemsGrouped = new ListCollectionView(StatusItems);
StatusItemsGrouped.GroupDescriptions.Add(new PropertyGroupDescription("GenericStatus"));
StatusItemsGrouped.SortDescriptions.Add(new SortDescription("GenericStatus", ListSortDirection.Descending));

基本上,我将数据分组到 DataGrid 基于名为 GenericStatus 的信息。除排序外,一切都很好。我现在想要实现的是按照降序对组进行排序(就像我的代码一样),但是上面的代码的问题在于,一旦用户单击某个列,排序就会被破坏。

Basically I am grouping data on a DataGrid based on info called GenericStatus. Everything is fine except the sorting. What I want to achieve now is to sort the groups in Descending order (as my code does), but the problem with the above code is that as soon as the user clicks on some column, the sorting is ruined.

我想保留组排序,但仍允许用户排序​​。我猜用户排序基本上是次要排序,即我想要这个: ORDER BY GenericStatus DESC,UsersColumnOfChoise ASC / DESC

I want to retain the group sorting, but still allow user sorting. The user sort will be basically a secondary sort I guess, i.e. I want this: ORDER BY GenericStatus DESC, UsersColumnOfChoise ASC/DESC.

推荐答案

我自己遇到了这个问题,我的解决方案是拦截Sorting事件,并让ICollectionView在ViewModel中进行排序,而不是依靠DataGrid来处理它。

I just ran into this problem myself and my solution was to intercept the Sorting event and let the ICollectionView do the sorting in the ViewModel instead of relying on the DataGrid to handle it.

XAML:

<DataGrid ItemsSource="{Binding StatusItemsGrouped}" Sorting="OnSorting_"/>

XAML.CS:

private void OnSorting_(object sender, DataGridSortingEventArgs e)
{
    var viewModel = DataContext as ViewModel;
    e.Handled = true;                                 // prevent DataGrid from sorting
    viewModel.SortItemSource(e.Column);               // perform sorting
    e.Column.SortDirection = viewModel.SortDirection; // set sort direction icon on column header
}

ViewModel:

ViewModel:

public class ViewModel 
{
    public ListCollectionView StatusItemsGrouped { get; set; }
    public ListSortDirection SortDirection { get; set; }
    public string SortColumn { get; set; }

    public void SortItemSource(string columnName)
    {
        if (String.Compare(SortColumn, columnName, true) == 0)
            SortDirection = ListSortDirection.Ascending;
        else
            SortDirection = ListSortDirection.Descending;
        SortColumn = columnName;
        using(StatusItemsGrouped.DeferRefresh()) {
            StatusItemsGrouped.GroupDescriptions.Clear();
            StatusItemsGrouped.SortDescriptions.Clear();
            StatusItemsGrouped.SortDescriptions.Add(new SortDescription(SortColumn, SortDirection));
            StatusItemsGrouped.GroupDescriptions.Add(new PropertyGroupDescription("GenericStatus"));
        }
        StatusItemsGrouped.Refresh();
    }
}

这篇关于如何在WPF中强制DataGrid组顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆