怎样才能当一个DataGrid列进行排序我被通知(不排序)通知、DataGrid

2023-09-02 02:03:33 作者:因你极尽温柔

我需要有一种在排序事件的一个的 的DataGrid 在WPF应用程序,但无法找到一个方法来得到它。

I need to have kind of an Sorted event for a DataGrid in a WPF application but cannot find a way to get it.

下面是我的尝试:

的DataGrid 提供了一个事件的 排序 ,但我不能使用它,因为它是打响了排序完成之前。该 EventArgs的给我这是排序的列,但不是它的排序方式,如果我得到的排序方向设置为原来的值。当然,我可以猜出它会为我知道,它翻转从无到上升并最终下降,但是这将是无解的,因为它会失败,如果控制的行为变化。

The DataGrid provides an event Sorting, but I cannot use it as it is fired before the sorting is done. The EventArgs give me the column which is sorted but not the way it is sorted and if I get the sort direction it is set to the old value. Of course I could guess what it will be as I know that it flips from none to ascending and finally to descending but that would be no solution as it would fail if the behavior of the control changes.

第二个尝试:

的DataGrid 有一个默认视图,它提供了访问的 SortDescriptionCollection 。这个系列拥有所有排序属性,但我没有看到让我告知任何变化的可能性。

The DataGrid has a default view which provides access to a SortDescriptionCollection. This collection holds all sorting properties but I don't see any possibility to let me inform about changes.

我不得不说,我正在寻找一个解决方案,尽可能的干净,因为它会在大型项目中使用上,我不能使用,如果环境的变化,这可能会失败的解决方案。

I have to say that I'm looking for a solution as clean as possible as it will be used in a large project on which I can't use solutions which could fail if the environment changes.

有谁从经验(或文件?)我怎么能解决这个问题,知道吗?

Does anyone know from experience (or documentation?) how I could solve this problem?

编辑:为了更清楚我想要实现:我需要了解哪些的DataGrid 列按哪个方向时,用户排序的列。这是没有必要这信息来排序本身后,它只是是正确的;)

To make more clear what I want to achieve: I need to get informed which DataGrid column is sorted in which direction when a user sort a column. It is not necessary that this information comes after the sorting itself, it just has to be correct ;)

推荐答案

我实现了排序DataGrid的事件我通过重写DataGrid中,如下所示:

I implemented the Sorted for the DataGrid event myself by overriding the DataGrid as follows:

public class ValueEventArgs<T> : EventArgs
{
    public ValueEventArgs(T value)
    {
        Value = value;
    }

    public T Value { get; set; }

}

public class DataGridExt : DataGrid
{
    public event EventHandler<ValueEventArgs<DataGridColumn>> Sorted;

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

        if (Sorted == null) return;
        var column = eventArgs.Column;
        Sorted(this, new ValueEventArgs<DataGridColumn>(column));
    }
}

为了使用它那么所有你需要做的是这样的:

In order to use it then all you need to do is this:

    private void Initialize()
    {
            myGrid.Sorted += OnSorted;
    }
    private void OnSorted(object sender, ValueEventArgs<DataGridColumn> valueEventArgs)
    {
    // Persist Sort...
    }