终端一体化运控平台
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.
 
 
 

77 lines
2.6 KiB

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