终端一体化运控平台
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

DataGridEx.cs 2.5 KiB

2 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Windows.Controls;
  7. namespace WPFDemo.Bb
  8. {
  9. public class DataGridEx : DataGrid
  10. {
  11. private List<ColumnAndOrder> _columnAndOrderList = new List<ColumnAndOrder>();
  12. public DataGridEx()
  13. {
  14. AutoGeneratingColumn += DataGridEx_AutoGeneratingColumn;
  15. AutoGeneratedColumns += DataGridEx_AutoGeneratedColumns;
  16. }
  17. private void DataGridEx_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
  18. {
  19. e.Cancel = true;//将创建过程标记为已取消,以阻止DataGrid将生成的列对象加入到列集合中.
  20. //从Attribute中读取显示名称.
  21. var displayName = ((System.ComponentModel.MemberDescriptor)e.PropertyDescriptor).DisplayName;
  22. if (!string.IsNullOrWhiteSpace(displayName))
  23. {
  24. e.Column.Header = displayName;
  25. }
  26. //从Attribute中读取顺序,以及是否自动生成列的标识.
  27. var attributes = ((System.ComponentModel.MemberDescriptor)e.PropertyDescriptor).Attributes;
  28. var order = 0;
  29. foreach (Attribute attribute in attributes)
  30. {
  31. if (attribute is DataGridColumnOrderAttribute orderAttribute)
  32. {
  33. order = orderAttribute.DataGridColumnOrder;
  34. }
  35. else if (attribute is DoNotAutoGenerateDataGridColumnAttribute)
  36. {
  37. //发现 DoNotAutoGenerateDataGridColumnAttribute 时,丢弃已生成的列
  38. return;
  39. }
  40. }
  41. //将创建的列及顺序保存
  42. _columnAndOrderList.Add(new ColumnAndOrder(order, e.Column));
  43. }
  44. private void DataGridEx_AutoGeneratedColumns(object sender, EventArgs e)
  45. {
  46. //按顺序将所有列加入到Columns集合中
  47. foreach (var columnAndOrder in _columnAndOrderList.OrderBy(v => v.Order))
  48. {
  49. Columns.Add(columnAndOrder.DataGridColumn);
  50. }
  51. _columnAndOrderList = null;
  52. }
  53. private class ColumnAndOrder
  54. {
  55. public ColumnAndOrder(int order, DataGridColumn dataGridColumn)
  56. {
  57. Order = order;
  58. DataGridColumn = dataGridColumn;
  59. }
  60. public int Order { get; }
  61. public DataGridColumn DataGridColumn { get; }
  62. }
  63. }
  64. }