我需要通过代码将此XAML样式应用于DataGrid的Cell:
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Setter Property="Foreground" Value="{Binding RelativeSource={RelativeSource Self}, Path=Item.Dif, Converter={StaticResource RedValues}}"/>
</Style>
</DataGrid.RowStyle>
到目前为止,在我的代码中,我可以在TextAlignmentProperty上应用Setter,但不能在前台应用:
Style style2 = new Style(typeof(DataGridCell));
style2.Setters.Add(new Setter(TextBlock.TextAlignmentProperty, TextAlignment.Right));
style2.Setters.Add(new Setter(TextBlock.ForegroundProperty, new RedValues()));
codb = new DataGridTextColumn();
codb.Binding = new Binding("Dif") {
StringFormat = "C",
ConverterCulture = new CultureInfo("pt-PT") };
codb.Header = "Dif";
codb.CellStyle = style2;
grid.Columns.Add(codb);
这是我的转换器类:
class RedValues: IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is decimal) {
decimal quantity = (decimal)value;
if (quantity < 0)
return Brushes.IndianRed;
if (quantity > 0)
return Brushes.ForestGreen;
return Brushes.Black;
}
return Brushes.Yellow;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
答案 0 :(得分:1)
如果你想从代码中为转换器分配绑定,你可以这样做。
style2.Setters.Add(new Setter(TextBlock.ForegroundProperty, new Binding("Item.Dif"){Converter = new RedValues()} ))};
根据您的情况 - 您可以按照自己的想法添加所有相关代码和路径绑定。