全部我有以下XAML以根据单元格内容是否为'帮助'在运行时更改单元格背景颜色。如何在单元格值更改时更新DataGrid单元格背景
<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更新。
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>
但是,这并没有奏效。 如何在单元格值更改并提交时更改背景单元格颜色?
谢谢你的时间。
什么是'Row'属性在这里?它总是作为'Unset'值在我尝试的小样本中传递。 –
我相信这是当前选定'DataGrid'的'Row' ... – MoonKnight
如果'value [1]'正确传递并且它没有'unset'值,您是否已经通过在转换器类中放置了'breakpoint'来检查? –