c# - WPF 中的数据网格 - 1 列默认排序

标签 c# wpf sorting datagrid

在 WPF 中,我有一个包含几列的 DataGrid。

默认情况下,有 1 个我想让它排序,但我找不到如何做到这一点。

XAML 中的 DataGrid 如下所示:

<DataGrid x:Name="LibraryView" ItemsSource="{Binding Path=Elements[Persons]}" IsReadOnly="True" LoadingRow="dg_LoadingRow">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Name" Binding="{Binding Path=Element[Name].Value}" IsReadOnly="True" />
                <DataGridTextColumn Header="Score" Binding="{Binding Path=Element[Score].Value}" IsReadOnly="True" />
                <DataGridTextColumn Header="Date" Binding="{Binding Path=Element[Date].Value}" IsReadOnly="True" />
            </DataGrid.Columns>
        </DataGrid>

它背后唯一的代码是:

public ScoreBoard()
{
    InitializeComponent();
    DataSet ds = dweMethods.DecryptAndDeserialize("ScoreData.xml");
    XElement TrackList = XElement.Parse(ds.GetXml());
    LibraryView.DataContext = TrackList;
}

我只是找不到如何让它默认按“分数”列排序。

谁能帮我指出正确的方向?

最佳答案

NOTE: Using a CollectionViewSource will provide you with more power and control in these situations. When you're learning WPF I recommend understanding how to use CollectionViewSource to solve this problem along with other collection related problems like Grouping and Filtering.

编辑:这可能是由于规范的更改。这个答案是基于使用 .NET 4.0 的,我没有研究这个解决方案是否适用于旧版本的框架。

鉴于此 XAML

<DataGrid x:Name="LibraryView" ItemsSource="{Binding Path=Elements[Persons]}" IsReadOnly="True" LoadingRow="dg_LoadingRow">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Name" Binding="{Binding Path=Element[Name].Value}" IsReadOnly="True" />
            <DataGridTextColumn Header="Score" Binding="{Binding Path=Element[Score].Value}" IsReadOnly="True" />
            <DataGridTextColumn Header="Date" Binding="{Binding Path=Element[Date].Value}" IsReadOnly="True" />
        </DataGrid.Columns>
    </DataGrid>

您需要做的就是选择一列并为该列指定排序方向。

<DataGrid x:Name="LibraryView" ItemsSource="{Binding Path=Elements[Persons]}" IsReadOnly="True" LoadingRow="dg_LoadingRow">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Name" Binding="{Binding Path=Element[Name].Value}" IsReadOnly="True" />
                <DataGridTextColumn Header="Score" Binding="{Binding Path=Element[Score].Value}" IsReadOnly="True" SortDirection="Ascending" />
                <DataGridTextColumn Header="Date" Binding="{Binding Path=Element[Date].Value}" IsReadOnly="True" />
            </DataGrid.Columns>
        </DataGrid>

这将默认按升序排列到第 2 列。

关于c# - WPF 中的数据网格 - 1 列默认排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8962923/

相关文章:

c# - 检索在 Func 中执行的调用方法的名称

c# - 从 UserControl 的 DependencyProperty 绑定(bind)不起作用

wpf - 如何删除 TabItem 内容的默认边距?

java - 如何在已排序的数组中插入数字

c# - 使用 JSON.NET 有条件地将 JSON 字符串或数组属性反序列化为 C# 对象?

c# - KeyDown 和 KeyUp 倍数

WPF:装饰 ViewModel?

c# - 这是MVVM不好的做法吗?

string - 比较二进制字符串(不包括字母数字)

java - 使用 Stream 按给定索引序列排序