全部,我有以下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
类处理'converion'/ color update。
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>
但这没效果。 如何在更改和提交单元格值时更改背景单元格颜色?
感谢您的时间。
答案 0 :(得分:1)
如果我可以假设您的数据网格绑定到视图模型中的项集合,那么对于特定列,您可以使用DataTrigger:
<DataGrid ItemsSource="{Binding Items}" ...>
<DataGrid.Columns>
... columns
<DataGridTextColumn Header="My column"
Binding="{Binding MyItem, UpdateSourceTrigger=PropertyChanged}">
<DataGridTextColumn.CellStyle>
<Style TargetType="{x:Type DataGridCell}">
<Style.Triggers>
<DataTrigger Binding="{Binding MyItem}" Value="Help">
<Setter Property="Background" Value="LightSalmon"/>
</DataTrigger>
</Style.Triggers>
</Style>
</DataGridTextColumn.CellStyle>
</DataGridTextColumn>
问题是如果你需要将它应用于所有列,在这种情况下你需要为每个列分别设置一个样式。