我们在winform中经常用到DataGridView,好像是自带排序功能的(点击对应列的表头会自动排序)。在UWP的DataGrid中不能自动排序,不过实现起来也不复杂,网上例程不多,但是我在微软MSDN上找到了非常详细的说明和例程。
1. DataGrid有一个自带的Sorting事件,在Xmal中为其添加对应的事件函数
<controls:DataGrid
x:Name="dg"
Height="600" Margin="12"
AutoGenerateColumns="False"
CanUserSortColumns="True"
Sorting="dg_Sorting">
<controls:DataGrid.Columns>
<controls:DataGridTextColumn Header="Range" Binding="{Binding Range}" Tag="Range"/>
<!-- Add more columns -->
</controls:DataGrid.Columns>
</controls:DataGrid>
2. 在对应事件函数中通过Linq排序数据源的对象(一般为对象的List),然后再重新绑定给DataGrid.
private void dg_Sorting(object sender, DataGridColumnEventArgs e)
{
//Use the Tag property to pass the bound column name for the sorting implementation
if (e.Column.Tag.ToString() == "Range")
{
//Use the Tag property to pass the bound column name for the sorting implementation
if (e.Column.Tag.ToString() == "Range")
{
//Implement sort on the column "Range" using LINQ
if (e.Column.SortDirection == null || e.Column.SortDirection == DataGridSortDirection.Descending)
{
dg.ItemsSource = new ObservableCollection<Mountain>(from item in _items
orderby item.Range ascending
select item);
e.Column.SortDirection = DataGridSortDirection.Ascending;
}
else
{
dg.ItemsSource = new ObservableCollection<Mountain>(from item in _items
orderby item.Range descending
select item);
e.Column.SortDirection = DataGridSortDirection.Descending;
}
}
// add code to handle sorting by other columns as required
// Remove sorting indicators from other columns
foreach (var dgColumn in dg.Columns)
{
if (dgColumn.Tag.ToString() != e.Column.Tag.ToString())
{
dgColumn.SortDirection = null;
}
}
}
}
3. 其中dgColumn.SortDirection属性是用来设置表头的小箭头(代表正序或者倒序)
MSDN原文地址如下: