WPF 精修篇 DataGrid 数据源排序

原文:WPF 精修篇 DataGrid 数据源排序

效果

WPF 精修篇 DataGrid 数据源排序

  1. <DataGrid x:Name="datagrid" ItemsSource="{Binding ElementName=Mwindow, Path=Preson}" Margin="0,0,0,20">
  2. <DataGrid.Columns>
  3. <DataGridTextColumn Binding="{Binding Name}" Header="Name"></DataGridTextColumn>
  4. <DataGridTextColumn Binding="{Binding Address}" Header="Address"></DataGridTextColumn>
  5. <DataGridTextColumn Binding="{Binding Age}" Header="Age"></DataGridTextColumn>
  6. </DataGrid.Columns>
  7. </DataGrid>
  8. <CheckBox x:Name="sort" Content="排序" HorizontalAlignment="Left" Margin="466,300,0,0" VerticalAlignment="Top" Checked="CheckBox_Checked"/>
  1. public partial class MainWindow : Window
  2. {
  3. public MainWindow()
  4. {
  5. InitializeComponent();
  6. Preson = new ObservableCollection<Preson>() {
  7. new Preson() { Name = "慧哥1", Address = "大连1", Age = 31 },
  8. new Preson() { Name = "慧哥2", Address = "大连2", Age = 32 },
  9. new Preson() { Name = "慧哥3", Address = "大连3", Age = 33 },
  10. new Preson() { Name = "慧哥4", Address = "大连4", Age = 34 },
  11. new Preson() { Name = "慧哥5", Address = "大连5", Age = 35 },
  12. new Preson() { Name = "123", Address = "大连6", Age = 12 },
  13. new Preson() { Name = "444", Address = "大连7", Age = 14 },
  14. new Preson() { Name = "222", Address = "大连8", Age = 33 },
  15. new Preson() { Name = "1312", Address = "大连9", Age = 22 }
  16. };
  17. }
  18. public ObservableCollection<Preson> Preson
  19. {
  20. get { return (ObservableCollection<Preson>)GetValue(PresonProperty); }
  21. set { SetValue(PresonProperty, value); }
  22. }
  23. // Using a DependencyProperty as the backing store for Preson. This enables animation, styling, binding, etc...
  24. public static readonly DependencyProperty PresonProperty =
  25. DependencyProperty.Register("Preson", typeof(ObservableCollection<Preson>), typeof(MainWindow), new PropertyMetadata(null));
  26. private void CheckBox_Checked(object sender, RoutedEventArgs e)
  27. {
  28. var cvs = CollectionViewSource.GetDefaultView(datagrid.ItemsSource);
  29. if(cvs!=null&&cvs.CanSort)
  30. {
  31. cvs.SortDescriptions.Clear();
  32. if (sort.IsChecked == true)
  33. {
  34. cvs.SortDescriptions.Add(new System.ComponentModel.SortDescription("Age", System.ComponentModel.ListSortDirection.Descending));
  35. }
  36. }
  37. }
  38. }

 

留作记录

 

上一篇:WPF DataGrid表头合并且动态添加列


下一篇:WPF 精修篇 DataGrid 筛选