在 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/