我想根据它的值更改单元格内容文本的字体和颜色,但我需要从代码中添加列。问题是表格显示了十六进制值,而不是对单元格值进行着色。
我在 XAML 资源中添加了:
<Style x:Key="MyStyle" TargetType="{x:Type TextBlock}">
<Setter Property="Foreground" Value="{Binding TextColor}" />
</Style>
以下代码行初始化列:
DataGridTextColumn column = new DataGridTextColumn();
column.Header = field.name;
column.Binding = new Binding(field.name)
{
Mode = BindingMode.TwoWay,
UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged,
Converter = new NameToBrushConverter()
};
column.ElementStyle = this.FindResource("MyStyle") as Style;
dgwDataMain.Columns.Add(column);
我的自定义功能:
public class NameToBrushConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return ((string)value == "asd") ? Brushes.Red : Brushes.Black;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return Binding.DoNothing;
}
}