试试: 助手:
public class ColumnNameAttribute : Attribute
{
public string Name { get; set; }
public TextAlignment TextAlignment { get; set; }
public string Color { get; set; }
public bool IsReadOnly { get; set; }
public double MinWidth { get; set; }
/// <summary>
/// Helper to fill column attributes: header name, text alignment, editability and background color
/// </summary>
/// <param name="name"></param>
/// <param name="textAlignment"></param>
/// <param name="isReadOnly"></param>
/// <param name="color"></param>
public ColumnNameAttribute(string name, TextAlignment textAlignment = TextAlignment.Left, bool isReadOnly = true, string color = "White")
{
Name = name;
TextAlignment = textAlignment;
Color = color;
IsReadOnly = isReadOnly;
}
public ColumnNameAttribute(string name, double minWidth, TextAlignment textAlignment= TextAlignment.Left, bool isReadOnly = true, string color = "White")
{
Name = name;
TextAlignment = textAlignment;
IsReadOnly = isReadOnly;
Color = color;
}
}
xaml.cs:
datagrid.AutoGeneratingColumn += dataGrid_AutoGeneratingColumn;
private void dataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
var desc = e.PropertyDescriptor as PropertyDescriptor;
var att = desc.Attributes[typeof(ColumnNameAttribute)] as ColumnNameAttribute;
if (att != null)
{
e.Column.IsReadOnly = att.IsReadOnly;
e.Column.CellStyle = new Style(typeof(DataGridCell));
switch (att.Color)
{
case "LightGreen":
//BorderBrushProperty looks better
e.Column.CellStyle.Setters.Add(new Setter(BackgroundProperty, new SolidColorBrush(Colors.PaleGreen)));
e.Column.CellStyle.Setters.Add(new Setter(TextBox.ToolTipProperty, "<Enter value>"));
break;
}
e.Column.Header = att.Name;
e.Column.CellStyle.Setters.Add(new Setter(TextBlock.TextAlignmentProperty, att.TextAlignment));
if (att.MinWidth > 0) e.Column.MinWidth = att.MinWidth;
}
}
项目等级:
public Example{
[ColumnName("My Custom Name", TextAlignment.Right, false, "LightGreen")]
public string Name {get; set;}
}
为DataGridCell创建一个隐式样式,并使用Converter将其设置为背景颜色。转换器需要知道该行的数据项和单元格所在的列,所以它可能需要是一个'MultiValueConverter'。转换器需要将数据项目转换为DataGridRow对象,获取Progress进度单元,然后根据Column决定返回哪种颜色。或者,您可以为DataGrid创建适当的后备对象,并将数据解析到这些对象中,这些对象将包含可绑定到的“Color”属性。我的偏好是#2。 – Rachel