在 WPF 中对 DataGrid 进行预排序 [英] Pre-sorting a DataGrid in WPF

查看:33
本文介绍了在 WPF 中对 DataGrid 进行预排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a DataGrid in 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.

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

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

推荐答案

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

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

就最初对集合进行排序而言,您必须使用 CollectionViewSource 并对其进行排序,然后将其分配为 DataGrid 的 ItemsSource.如果您在 XAML 中执行此操作,那么它就像:

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:

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

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

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

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

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

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

这篇关于在 WPF 中对 DataGrid 进行预排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆