J4N*_*J4N 5 c# sorting wpf datagrid
我有一个UserControl,它基本上只包含一个DataGrid。在此DataGrid中,我有一个事件列表(严重性-日期-消息)。用户控制是通过结合ViewModelLocator的MVVMLight Toolkit。
我添加了两件事:
在我的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" >
我也有SortedDirection设置DataGridTextColumn.SortDirection:
<DataGridTextColumn Binding="{Binding EventTime}"  Header="Time" IsReadOnly="True" SortDirection="Descending"/>
当我检查设计器时,我看到一个小箭头,表明DataGrid已正确排序。
但是,当我启动该应用程序时,列表未排序,箭头不在此处。如果我单击该列以对其进行排序,那么它将对所有内容正确地进行排序,只是默认值似乎无效。
我想念什么?(这个dataGrid / column甚至都没有命名,因此我无法尝试通过其他方式对其进行编辑)。
(最初,我只在SortDirection上使用DataGridTextColumn。结果相同)
关于“小箭头”请检查此处: 在 XAML 中对 DataGrid 进行排序时未反映 ColumnHeader arrows
对于更复杂的答案:Pre-sorting a DataGrid in WPF
我认为主要部分是:
注意:“scm”命名空间前缀映射到 SortDescription 类所在的 System.ComponentModel。
Run Code Online (Sandbox Code Playgroud)xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase"
编辑
每当其 ItemsSource 发生更改时,DataGrid 就会删除 SortDescriptions 和 GroupDescriptions。这是必要的,因为与其他 ItemsControl 不同,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);
    }