0
votes

I'm using the WPF datagrid and need to let the user sort the columns only in ascending direction and not to allow the descending direction.

Is there an easy way to do that ?

the trivial way would be to implement my own sort using collection view source, and listening to mouse click event on the column header.

2

2 Answers

0
votes

You can get it also using Behaviors. Because it is better to use behaviors in such situations.

This is what you are going to do:

First of all add SortOnlyAscending.cs class to your Project.

public class SortOnlyAscending:Behavior<DataGrid> 
{
    protected override void OnAttached()
    {
        AssociatedObject.Sorting += AssociatedObject_Sorting;
        base.OnAttached();
    }

    protected override void OnDetaching()
    {
        AssociatedObject.Sorting -= AssociatedObject_Sorting;
        base.OnDetaching();
    }

    private void AssociatedObject_Sorting(object sender, DataGridSortingEventArgs e)
    {
        e.Column.SortDirection = ListSortDirection.Ascending;
    }
}

Then in .xaml you going to add this behavior to your DataGrid like that:

   <DataGrid>
        <i:Interaction.Behaviors>
           <local:SortOnlyAscending/>
        </i:Interaction.Behaviors>
   </DataGrid>

Also you have to add two namepsaces to your .xaml also for using your behavior. The name of my project was WpfApplication1, so you gonna chnage it as you want.

 xmlns:local ="clr-namespace:WpfApplication1" 
 xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"

That's it. Also you need System.Windows.interactivity.dll for using Behavior class. You can download it from NUget Package Manager also. Here is link.

0
votes

Ok, I got it ...

just handle the sorting event of the DataGrid:

 private void DataGrid_OnSorting(object sender, DataGridSortingEventArgs e)
    {
        e.Column.SortDirection = ListSortDirection.Ascending;
    }