Dan*_*986 28 c# sorting wpf 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>
Run Code Online (Sandbox Code Playgroud)
它背后唯一的代码是:
public ScoreBoard()
{
InitializeComponent();
DataSet ds = dweMethods.DecryptAndDeserialize("ScoreData.xml");
XElement TrackList = XElement.Parse(ds.GetXml());
LibraryView.DataContext = TrackList;
}
Run Code Online (Sandbox Code Playgroud)
我找不到的是默认情况下如何按"分数"列进行排序.
任何人都可以帮我指出正确的方向吗?
Som*_*Guy 46
注意:在这些情况下,使用CollectionViewSource将为您提供更多功能和控制.当您学习WPF时,我建议您了解如何使用CollectionViewSource解决此问题以及其他与集合相关的问题,例如分组和过滤.
编辑:这可能是由于规范的变化.这个答案是基于使用.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>
Run Code Online (Sandbox Code Playgroud)
您需要做的就是选择一列并指定该列的排序方向.
<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>
Run Code Online (Sandbox Code Playgroud)
这将默认按向上方向排序到第二列.
dob*_*lak 10
我在下面的第一列描述了如何对代码进行排序:初始DataGrid排序
您可以调整代码以按特定的所需列进行排序,尽管整个方法看起来很混乱.
如果你想在XAML中做...可能有用的是设置CollectionViewSource.SortDescriptions:
<CollectionViewSource x:Key="cvs" Source="{StaticResource myItemsSource}">
<CollectionViewSource.SortDescriptions>
<scm:SortDescription PropertyName="MyPropertyName" Direction="Ascending"/>
</CollectionViewSource.SortDescriptions>
</CollectionViewSource>
Run Code Online (Sandbox Code Playgroud)
但我从未尝试过后者.