我知道在使用转换器填充数据网格时如何更改单元格的文本颜色,但是在单元格值更改为某个值后,我找不到与更改文本颜色相关的任何内容。我需要从代码中执行此操作,因为我需要检查的值并不总是相同的。
public class NameToBrushConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
DataGridCell cell = values[0] as DataGridCell;
Session_Counter.CoreWindow.BindableDynamicDictionary row = values[1] as Session_Counter.CoreWindow.BindableDynamicDictionary;
CoreWindow.Fields field = CoreWindow.fields.Find(o => o.name == cell.Column.Header.ToString());
if (cell != null && row != null && field.color != null)
{
foreach (string str in field.color)
{
List<string> str2 = new List<string>(str.Split(new string[] { "<&p>" }, StringSplitOptions.None).ToList());
if (str2[0].ToString().StartsWith("VALUE = "))
{
if (str2[0].Substring(8) == row[cell.Column.Header.ToString()].ToString())
return new SolidColorBrush((Color)ColorConverter.ConvertFromString(str2[5]));
}
}
}
return Brushes.Black;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
XAML:
<DataGrid AutoGenerateColumns="False" Name="dgwDataMain" CellEditEnding="dgwDataMain_CellEditEnding" SelectionChanged="dgwDataMain_SelectionChanged" PreviewKeyDown="dgwDataMain_PreviewKeyDown" CanUserAddRows="False" Grid.Row="2" Width="Auto" MaxColumnWidth="300" Height="Auto" CanUserReorderColumns="False" CanUserResizeRows="False" >
<DataGrid.CellStyle>
<Style TargetType="DataGridCell">
<Setter Property="Foreground">
<Setter.Value>
<MultiBinding Converter="{StaticResource nameToBC}">
<Binding RelativeSource="{RelativeSource Self}"/>
<Binding Path="."/>
</MultiBinding>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="DataGridCell.IsSelected" Value="True">
<Setter Property="Background" Value="#CCDAFF" />
</Trigger>
</Style.Triggers>
</Style>
</DataGrid.CellStyle>
</DataGrid>