我想根据它的值更改单元格内容文本字体和颜色,但我需要从代码中添加列。问题是,表显示我十六进制值,而不是着色单元格值。
我添加了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;
}
}
您可以使用MultiValueConverter
实现这一点。
的例子:
DataGridTextColumn column = new DataGridTextColumn();
column.Header = "Name";
column.Binding = new Binding("Name")
{
Mode = BindingMode.TwoWay,
UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
};
column.ElementStyle = this.FindResource("MyStyle") as Style;
grid.Columns.Add(column);
List<Foo> _source = new List<Foo>
{
new Foo{ Name ="test1"},
new Foo{ Name ="test2"},
new Foo{ Name ="test3"}
};
grid.ItemsSource = _source;
Foo类:
class Foo
{
public string Name { get; set; }
}
风格XAML:
<local:NameToBrushConverter x:Key="nameToBC" />
<Style x:Key="MyStyle" TargetType="{x:Type TextBlock}">
<Setter Property="Foreground" >
<Setter.Value>
<MultiBinding Converter="{StaticResource nameToBC}" >
<Binding Path="." />
</MultiBinding>
</Setter.Value>
</Setter>
</Style>
MultiValueConverter代码:
class NameToBrushConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
Foo item = values[0] as Foo;
if (item != null)
{
if (item.Name == "test2")
return Brushes.Red;
else
return Brushes.Black;
}
return Brushes.Black;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}