Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
220 views
in Technique[技术] by (71.8m points)

.net - How can I be notified if a DataGrid column is sorted (and not sorting)

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

Here is what I tried:

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.

Second try:

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?

Edit: 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 ;)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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...
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...