在WPF中预先排序DataGrid [英] Pre-sorting a DataGrid in WPF

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

问题描述

我在WPF应用程序中有一个 DataGrid ,其中有几列,包括名称列。如果用户切换到特定视图,我希望数据按名称进行预排序(我想要一个排序箭头显示在名称头中,就像用户点击了该标题一样)。但是,我找不到预期的属性来实现这一点。我正在寻找像 SortColumn SortColumnIndex SortDirection 等等。

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控件, a href =http://msdn.microsoft.com/en-us/library/system.windows.controls.datagrid.canusersortcolumns(VS.100,default).aspx =noreferrer> 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并设置该类型,然后将其指定为Dat的ItemsSource aGrid。如果您在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命名空间前缀映射到System.ComponentModel SortDescription类生活。

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天全站免登陆