Ignacio Soler Garcia
Ignacio Soler Garcia

Reputation: 21855

How to disable multiple column sorting on a wpf DataGrid?

I need to disable multiple column sorting on a DataGrid. Is this possible?

Upvotes: 1

Views: 1567

Answers (2)

willkendall
willkendall

Reputation: 69

I had success by subscribing to the DataGrid_Sorting event and setting the args' Handled property to true:

private void ResultsDataGrid_Sorting(object sender, DataGridSortingEventArgs e)
{
    if (Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift))
    {
        e.Handled = true;
    }
}

Upvotes: 2

blindmeis
blindmeis

Reputation: 22435

you can create a behavior and handle the sort be your self. the following is not tested :)

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

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

    void AssociatedObjectSorting(object sender, DataGridSortingEventArgs e)
    {
        var view = AssociatedObject.ItemsSource as ICollectionView;
        var propertyname = e.Column.SortMemberPath;

        e.Column.SortDirection = this.GetSortArrowForColumn(e.Column);

        if (view == null)
            return;

        view.SortDescriptions.Clear();            
        var sort = new SortDescription(propertyname, (ListSortDirection)e.Column.SortDirection);
        view.SortDescriptions.Add(sort);


        e.Handled = true;
    }


    private ListSortDirection GetSortArrowForColumn(DataGridColumn col)
    {
        if (col.SortDirection == null)
        {
           return ListSortDirection.Ascending;
        }
        else
        {
            return col.SortDirection == ListSortDirection.Ascending ? ListSortDirection.Descending : ListSortDirection.Ascending;
        }
    }
   }

xaml

 <DataGrid ...>
    <i:Interaction.Behaviors>
            <Kadia:DataGridICollectionViewSortMerkerBehavior />
    </i:Interaction.Behaviors>

Upvotes: 0

Related Questions