|
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576 |
- using BPASmartClient.CustomResource.Pages.Model;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows.Controls;
-
- namespace BPASmartClient.CustomResource.UserControls
- {
- public class DataGridEx : DataGrid
- {
- private List<ColumnAndOrder> _columnAndOrderList = new List<ColumnAndOrder>();
-
- public DataGridEx()
- {
- AutoGeneratingColumn += DataGridEx_AutoGeneratingColumn;
- AutoGeneratedColumns += DataGridEx_AutoGeneratedColumns;
- }
-
- private void DataGridEx_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
- {
-
- e.Cancel = true;//将创建过程标记为已取消,以阻止DataGrid将生成的列对象加入到列集合中.
-
- //从Attribute中读取显示名称.
- var displayName = ((System.ComponentModel.MemberDescriptor)e.PropertyDescriptor).DisplayName;
- if (!string.IsNullOrWhiteSpace(displayName))
- {
- e.Column.Header = displayName;
- }
-
- //从Attribute中读取顺序,以及是否自动生成列的标识.
- var attributes = ((System.ComponentModel.MemberDescriptor)e.PropertyDescriptor).Attributes;
- var order = 0;
- foreach (Attribute attribute in attributes)
- {
- if (attribute is DataGridColumnAttribute orderAttribute)
- {
- order = orderAttribute.DataGridColumn;
- }
- else if (attribute is DoNotAutoGenerateDataGridColumnAttribute)
- {
- //发现 DoNotAutoGenerateDataGridColumnAttribute 时,丢弃已生成的列
- return;
- }
- }
-
- //将创建的列及顺序保存
- _columnAndOrderList.Add(new ColumnAndOrder(order, e.Column));
- }
-
- private void DataGridEx_AutoGeneratedColumns(object sender, EventArgs e)
- {
- //按顺序将所有列加入到Columns集合中
- foreach (var columnAndOrder in _columnAndOrderList.OrderBy(v => v.Order))
- {
- Columns.Add(columnAndOrder.DataGridColumn);
- }
- _columnAndOrderList = null;
- }
-
- private class ColumnAndOrder
- {
- public ColumnAndOrder(int order, DataGridColumn dataGridColumn)
- {
- Order = order;
- DataGridColumn = dataGridColumn;
- }
-
- public int Order { get; }
-
- public DataGridColumn DataGridColumn { get; }
- }
- }
- }
|