所有,我有以下 XAML 在运行时根据单元格内容是否为“帮助”来更改单元格背景颜色。
<UserControl.Resources>
<local:CellColorConverter x:Key ="cellColorConverter"/>
</UserControl.Resources>
<DataGrid x:Name="dataGrid" AlternatingRowBackground="Gainsboro"
AlternationCount="2" HorizontalAlignment="Stretch"
VerticalAlignment="Stretch">
<DataGrid.CellStyle>
<Style TargetType="DataGridCell" >
<Setter Property="Background">
<Setter.Value>
<MultiBinding Converter="{StaticResource cellColorConverter}" >
<MultiBinding.Bindings>
<Binding RelativeSource="{RelativeSource Self}"/>
<Binding Path="Row"/>
</MultiBinding.Bindings>
</MultiBinding>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Background" Value="#FF007ACC"/>
<Setter Property="Foreground" Value="White"/>
</Trigger>
</Style.Triggers>
</Style>
</DataGrid.CellStyle>
</DataGrid>
该类CellColorConverter
处理“转换”/颜色更新。
public class CellColorConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
if (values[1] is DataRow)
{
//Change the background of any cell with 1.0 to light red.
var cell = (DataGridCell)values[0];
var row = (DataRow)values[1];
var columnName = cell.Column.SortMemberPath;
if (row[columnName].ToString().CompareTo("Help") == 0)
return new SolidColorBrush(Colors.LightSalmon);
}
return SystemColors.AppWorkspaceColor;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new System.NotImplementedException();
}
}
这在加载数据时有效,但如果用户在单元格中键入“帮助”,我也希望更新颜色。所以我尝试将绑定修改为
<Setter Property="Background">
<Setter.Value>
<MultiBinding Converter="{StaticResource cellColorConverter}" >
<MultiBinding.Bindings>
<Binding RelativeSource="{RelativeSource Self}" // Changed this!
Mode="TwoWay" UpdateSourceTrigger="PropertyChanged"/>
<Binding Path="Row"/>
</MultiBinding.Bindings>
</MultiBinding>
</Setter.Value>
但这并没有奏效。更改和提交单元格值时如何更改背景单元格颜色?
谢谢你的时间。