在 WPF 中对 DataGrid 进行预排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1627149/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 21:07:53  来源:igfitidea点击:

Pre-sorting a DataGrid in WPF

wpfxamlsortingdatagridwpftoolkit

提问by devuxer

I have a DataGridin WPF app with several columns, including a Name column. If the users switches to a particular view, I want the data to be pre-sorted by Name (and I'd like a sort arrow to appear in the Name header just as if the user had clicked that header). However, I can't find the expected properties to make this happen. I was looking for something like SortColumn, SortColumnIndex, SortDirection, etc.

我有一个DataGrid包含多列的 WPF 应用程序,包括一个名称列。如果用户切换到特定视图,我希望数据按名称预先排序(并且我希望排序箭头出现在名称标题中,就像用户单击了该标题一样)。但是,我找不到实现此目的的预期属性。我正在寻找诸如SortColumn, SortColumnIndex, 之类的东西SortDirection

Is it possible to specify the default sort column and direction in markup (XAML) or is that not supported by the WPF Toolkit DataGrid?

是否可以在标记 (XAML) 中指定默认排序列和方向,或者 WPF Toolkit 不支持DataGrid

回答by Drew Marsh

Assuming you're talking about the WPF Toolkit DataGrid control, you need only set the CanUserSortColumns propertyto true and then set the SortMemberPath propertyof each DataGridColumn in the DataGrid.

假设您正在讨论 WPF Toolkit DataGrid 控件,您只需将CanUserSortColumns 属性设置为 true,然后设置DataGrid 中每个 DataGridColumn的 SortMemberPath 属性

As far as sorting the collection initially, you must use a CollectionViewSource and set the sort on that and then assign that as the ItemsSource of your DataGrid. If you're doing this in XAML then it would be as easy as:

至于最初对集合进行排序,您必须使用 CollectionViewSource 并在其上设置排序,然后将其分配为 DataGrid 的 ItemsSource。如果您在 XAML 中执行此操作,那么它将非常简单:

<Window.Resources>
    <CollectionViewSource x:Key="MyItemsViewSource" Source="{Binding MyItems}">
        <CollectionViewSource.SortDescriptions>
           <scm:SortDescription PropertyName="MyPropertyName"/>
        </CollectionViewSource.SortDescriptions>
    </CollectionViewSource>
</Window.Resources>

<DataGrid ItemsSource="{StaticResource MyItemsViewSource}">

</DataGrid>

NOTE:the "scm" namespace prefix maps to System.ComponentModel where the SortDescription class lives.

注意:“scm”命名空间前缀映射到 SortDescription 类所在的 System.ComponentModel。

xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase"

EDIT:I think enough people got help from this post, that this upvoted comment should be included in this answer:

编辑:我认为有足够多的人从这篇文章中得到了帮助,这个被赞成的评论应该包含在这个答案中:

I had to use this to get it to work:

我不得不使用它来让它工作:

<DataGrid ItemsSource="{Binding Source={StaticResource MyItemsViewSource}}">

回答by Matt

I know this is an old post but in addition to Drew Marsh's answer and in response to DanM's issue with the column header's arrows not appearing... You need to add the SortDirection property to the DataGridColumn:

我知道这是一篇旧帖子,但除了 Drew Marsh 的回答以及响应 DanM 的问题,列标题的箭头没有出现......您需要将 SortDirection 属性添加到 DataGridColumn:

<DataGridTextColumn Header="Name" Binding="{Binding Name}" SortDirection="Ascending" />

I posted a question about this and found the answer a few days later:

我发布了一个关于这个的问题,几天后找到了答案:

ColumnHeader arrows not reflected when sorting a DataGrid in XAML

在 XAML 中对 DataGrid 进行排序时未反映 ColumnHeader 箭头

回答by Sukhjeet

When you see ItemsSource doesn't support CollectionViewSource exception then you can set the DataContext of DataGrid as 'MyItemsViewSource' and ItemsSource as {Binding} like this:

当您看到 ItemsSource 不支持 CollectionViewSource 异常时,您可以将 DataGrid 的 DataContext 设置为“MyItemsViewSource”,将 ItemsSource 设置为 {Binding},如下所示:

<DataGrid DataContext="{StaticResource MyItemsViewSource}" ItemsSource="{Binding}">
</DataGrid>

回答by Václav Dajbych

When you see ItemsSource doesn't support CollectionViewSourceexception, you can sort collection by Linq before you refer it to a DataGrid:

当您看到ItemsSource doesn't support CollectionViewSource异常时,您可以在将集合引用到 DataGrid 之前按 Linq 对其进行排序:

ObservableCollection<MyDataClass> myCollection = new ObservableCollection<MyDataClass>();
dataGrid.ItemsSource = from item in myCollection orderby item select item;

You have to implement IComparableinterface to MyDataClass:

你必须实现IComparable接口MyDataClass

public class MyDataClass : IComparable<MyDataClass> {
    public int CompareTo(Classified other) {
        return other.Value.CompareTo(this.Value); // DESC
        return this.Value.CompareTo(other.Value); // ASC
    }
}

回答by Pramod Pawar

This works for me.

这对我有用。

ListSortDirection sortDirection;
int selectedColumnIndex;
private void customerDataGrid_Sorting(object sender, DataGridSortingEventArgs e)
{
    selectedColumnIndex = e.Column.DisplayIndex;
    sortDirection = (e.Column.SortDirection == ListSortDirection.Ascending ? ListSortDirection.Descending: ListSortDirection.Ascending);
}

private void applySortDescriptions(ListSortDirection listSortDirection)
{
    //Clear current sort descriptions 
    customerDataGrid.Items.SortDescriptions.Clear();

    //Get property name to apply sort based on desired column 
    string propertyName = customerDataGrid.Columns[selectedColumnIndex].SortMemberPath;

    //Add the new sort description 
    customerDataGrid.Items.SortDescriptions.Add(new SortDescription(propertyName, listSortDirection));

    //apply sort 
    applySortDirection(listSortDirection);

    //refresh items to display sort 
    customerDataGrid.Items.Refresh();
}

private void applySortDirection(ListSortDirection listSortDirection)
{
    customerDataGrid.Columns[selectedColumnIndex].SortDirection = listSortDirection;
}