码迷,mamicode.com
首页 > 编程语言 > 详细

WPF 精修篇 DataGrid 数据源排序

时间:2019-12-21 00:22:56      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:ted   script   extc   key   str   typeof   ado   can   ati   

原文: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 数据源排序

标签:ted   script   extc   key   str   typeof   ado   can   ati   

原文地址:https://www.cnblogs.com/lonelyxmas/p/12075451.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!