XAML 已忽略数据网格排序方向

dl5txlt9  于 2022-12-07  发布在  其他
关注(0)|答案(4)|浏览(134)

我想在启动时指定默认排序,但仍允许用户通过单击列标题进行排序。遗憾的是,SortDirection属性在设置时被忽略了-也就是说,我们得到了正确的列标题箭头,但没有进行排序。
手动点击标题,对数据进行正确排序,所以不是排序本身。这是我使用的简化版本:

<DataGrid ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=CurrentView}" AutoGenerateColumns="False">
    <DataGrid.Columns>
        <DataGridTextColumn Header="Header 1" Binding="{Binding ApplicationName}"/>
        <DataGridTextColumn Header="Header 2" 
               Binding="{Binding TotalTime}" SortDirection="Descending"/>
    </DataGrid.Columns>
</DataGrid>

更新:我也尝试按照建议将SortDescriptions添加到ICollectionView中,但没有好的结果。这是否与我动态地向集合中添加新项有关?也就是说,在启动时列表是空的,并且填充速度很慢,可能sortdescription只应用了一次?

kmynzznz

kmynzznz1#

看看这个MSDN Blog
从以上链接:
SortDirection实际上并不对列进行排序。
DataGridColumn.SortDirection用于对DataGridColumnHeader中的可视箭头进行排队,使其指向上、下或不显示。若要在不单击DataGridColumnHeader的情况下对列进行实际排序,可以通过编程方式设置DataGrid.Items.SortDescriptions。

bcs8qyzn

bcs8qyzn2#

我没有任何个人经验,但我找到了this rather helpful article
实际上,您需要将SortDescription添加到DataGrid绑定到的CollectionViewSource。

sqougxex

sqougxex3#

这篇文章非常有帮助。我能够用它找到一个稍微简单的解决方案。下面是我的解决方案的一个片段。

XAML格式

<DataGrid HorizontalAlignment="Stretch" VerticalAlignment="Stretch" 
            AutoGenerateColumns="False" ItemsSource="{Binding LogLister.Logs}"              
            IsReadOnly="True" >

            <DataGrid.Columns>                  

                <DataGridTextColumn Binding="{Binding TimeStampLocal}" Header="Time" x:Name="ColTimeStamp" />

                <DataGridTextColumn Binding="{Binding Text}" Header="Text"/>
            </DataGrid.Columns>
        </DataGrid>

代码

// Using a DependencyProperty as the backing store for ViewModel.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty ViewModelProperty =
        DependencyProperty.Register("ViewModel", typeof(LogViewerViewModel), typeof(LogViewerControl),
           new UIPropertyMetadata(null,pf_viewModelChanged));

    private static void pf_viewModelChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
    {
        var control = (LogViewerControl)o;

        control.ColTimeStamp.SortDirection = ListSortDirection.Descending;

        var vm = e.NewValue as LogViewerViewModel;

        if (vm != null)
        {   
            ICollectionView collectionView = CollectionViewSource.GetDefaultView(vm.LogLister.Logs);
            collectionView.SortDescriptions.Add(new SortDescription("TimeStampLocal", ListSortDirection.Descending));
        }
    }
k0pti3hp

k0pti3hp4#

简而言之,没有一种快速、简单的方法可以做到这一点。我编写了自己的自定义排序器,它在ObservableCollections上使用Move方法。我重写了“DataGridSorting”事件,并调用了自己的方法来简化这一过程。我不打算在这里发布代码,因为我认为它对您的问题来说太夸张了。
我会说坚持使用我上面的评论,使用一个集合视图源和一个排序描述(主管技术最初张贴)。

相关问题