【问题标题】:WPF DataGrid: Specify a default sortWPF DataGrid:指定默认排序
【发布时间】:2015-06-22 14:24:10
【问题描述】:

我有一个 UserControl,它基本上只包含一个 DataGrid。 在这个 DataGrid 中,我有一个事件列表(严重性 - 日期 - 消息)。 用户控件通过MVVMLight ToolkitViewModelLocator绑定。

我添加了两件事:

在我的 UserControl 资源中:

<UserControl.Resources>
    <CollectionViewSource x:Key="SortedEvents" Source="{Binding Events}">
        <CollectionViewSource.SortDescriptions>
            <componentModel:SortDescription PropertyName="EventTime" Direction="Descending"/>
        </CollectionViewSource.SortDescriptions>
    </CollectionViewSource>
</UserControl.Resources>

DataGrid 使用的:

<DataGrid ItemsSource="{Binding Source={StaticResource SortedEvents}}" AutoGenerateColumns="False" >

我还在DataGridTextColumn.SortDirection 上设置了SortedDirection

<DataGridTextColumn Binding="{Binding EventTime}"  Header="Time" IsReadOnly="True" SortDirection="Descending"/>

当我检查设计器时,我看到显示 DataGrid 已正确排序的小箭头。

但是当我启动应用程序时,列表没有排序,箭头不在这里。如果我单击该列对其进行排序,它将正确排序所有内容,它只是似乎不起作用的默认值。

我错过了什么? (这个 dataGrid/column 甚至没有命名,所以我无法尝试通过其他方式编辑它们)。

(最初我在DataGridTextColumn 上只有SortDirection。结果相同)

【问题讨论】:

    标签: c# wpf sorting datagrid


    【解决方案1】:

    关于这里的“小箭头”检查: ColumnHeader arrows not reflected when sorting a DataGrid in XAML

    对于更复杂的答案:Pre-sorting a DataGrid in WPF

    我认为主要部分是:

    注意:“scm”命名空间前缀映射到 System.ComponentModel,其中 SortDescription 类存在。

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

    编辑

    DataGrid 在其 ItemsSource 更改时删除 SortDescriptions 和 GroupDescriptions。这是必要的,因为与其他 ItemsControls 不同,DataGrid 本身会在用户单击列标题时添加 SortDescriptions,如果它们与新的 ItemsSource 不兼容,则保持原样可能会崩溃。

    protected override void OnItemsSourceChanged(IEnumerable oldValue, IEnumerable newValue)
        {
            if (SetupSortDescriptions != null && (newValue != null)) 
                SetupSortDescriptions(this, new ValueEventArgs<CollectionView>((CollectionView)newValue)); 
    
            base.OnItemsSourceChanged(oldValue, newValue);
        }
    

    【讨论】:

    • 请再读一遍我的问题,你基本上给了我两件我已经做过和描述过的事情。
    【解决方案2】:

    您似乎只需将 IsLiveSortingRequested="True" 添加到您的 CollectionViewSource。

     <UserControl.Resources>
        <CollectionViewSource x:Key="SortedEvents" Source="{Binding Events}" IsLiveSortingRequested="True">
            <CollectionViewSource.SortDescriptions>
                <componentModel:SortDescription PropertyName="EventTime" Direction="Descending"/>
            </CollectionViewSource.SortDescriptions>
        </CollectionViewSource>
    </UserControl.Resources>
    

    这对我有用

    【讨论】:

      猜你喜欢
      • 2015-05-13
      • 2012-02-16
      • 1970-01-01
      • 2017-11-17
      • 2016-09-18
      • 1970-01-01
      • 2013-12-31
      • 2015-04-14
      • 1970-01-01
      相关资源
      最近更新 更多