在WPF中预排序DataGrid

dev*_*xer 26 sorting wpf xaml datagrid wpftoolkit

我有一个DataGrid包含多个列的WPF应用程序,包括一个Name列.如果用户切换到特定视图,我希望数据按名称进行预排序(我希望排序箭头显示在Name标题中,就像用户点击了该标题一样).但是,我无法找到实现这一目标的预期属性.我一直在寻找这样的事情SortColumn,SortColumnIndex,SortDirection,等.

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

Dre*_*rsh 44

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

至于最初对集合进行排序,您必须使用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>
Run Code Online (Sandbox Code Playgroud)

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

xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase"
Run Code Online (Sandbox Code Playgroud)

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

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

<DataGrid ItemsSource="{Binding Source={StaticResource MyItemsViewSource}}">
Run Code Online (Sandbox Code Playgroud)

  • 我不得不使用<DataGrid ItemsSource ="{Binding Source = {StaticResource MyItemsViewSource}}">来使其工作. (12认同)
  • 是的:)这比我想要的更接近,谢谢.唯一的问题是排序箭头没有出现在表排序的列的标题中.我可以忍受这一点,但是箭头会让用户更清楚一下排序列是什么.对于任何试图执行此操作的人来说,只需要一个注释,您需要引用`WindowsBase`来使用`System.ComponentModel`.一旦添加了引用,就需要:`xmlns:scm ="clr-namespace:System.ComponentModel; assembly = WindowsBase"`. (5认同)

Mat*_*att 18

我知道这是一个老帖子,但除了Drew Marsh的答案之外,为了回应DanM的问题,列标题的箭头没有出现......你需要将SortDirection属性添加到DataGridColumn:

<DataGridTextColumn Header="Name" Binding="{Binding Name}" SortDirection="Ascending" />
Run Code Online (Sandbox Code Playgroud)

我发布了一个关于此的问题并在几天后找到答案:

在XAML中排序DataGrid时,未反映ColumnHeader箭头


小智 5

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

<DataGrid DataContext="{StaticResource MyItemsViewSource}" ItemsSource="{Binding}">
</DataGrid>
Run Code Online (Sandbox Code Playgroud)

  • 我一直回到这篇文章(今年第三次)因为我忘记做这个非常重要的部分/拼图!谢谢您的发布。 (2认同)