简体   繁体   English

如何在WPF DataGrid上禁用多列排序?

[英]How to disable multiple column sorting on a wpf DataGrid?

I need to disable multiple column sorting on a DataGrid. 我需要在DataGrid上禁用多列排序。 Is this possible? 这可能吗?

I had success by subscribing to the DataGrid_Sorting event and setting the args' Handled property to true: 通过订阅DataGrid_Sorting事件并将args的Handled属性设置为true,我获得了成功:

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

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 XAML

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM