大厂的控件会自动应用注解,而WPF自带的不能应用,需要手动实现
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
using System.Windows.Controls;
namespace WPF.UserControl
{
public class XGrid : DataGrid
{
public XGrid()
{
AutoGeneratingColumn += (o, e) =>
{
var result = e.PropertyName;
var p = (e.PropertyDescriptor as PropertyDescriptor).ComponentType.GetProperties().FirstOrDefault(x => x.Name == e.PropertyName);
if (p != null)
{
var found = p.GetCustomAttribute<DisplayAttribute>();
if (found != null) {
result = found.Name;
if ( found.GetAutoGenerateField() == false)
{
e.Cancel = true;
return;
}
}
}
e.Column.Header = result;
};
}
}
}
<Style BasedOn="{StaticResource MaterialDesignDataGrid}" TargetType="{x:Type uc:XGrid}" />
如果直接应用,会造成样式丢失,需要BasedOn一下。