我的 C# wpf 应用程序中有一个Datagrid (DataGridMeterValues)。每次用户退出单元格的编辑模式时,都会触发CellEditEnding事件。
现在我希望在触发事件时更改单元格的背景。
这是我到目前为止得到的:
private void DataGridMeterValues_CellEditEnding(object sender, System.Windows.Controls.DataGridCellEditEndingEventArgs e)
{
// Code to change background color here
}
我可以使用以下代码更改整行的背景:
e.Row.Background = Brushes.Yellow;
现在我的问题是,我可以做同样的事情,但只针对 1 个单元格(选定的单元格)而不是整行
编辑:这是数据网格的 XAML
<DataGrid Grid.Row="3" Grid.Column="1" AutoGenerateColumns="False" Name="DataGridMeterValues" ItemsSource="{Binding Path=MeterValuesList, UpdateSourceTrigger=PropertyChanged}" AlternatingRowBackground="LightGray" BorderBrush="Gray" BorderThickness="1" FrozenColumnCount="0" CanUserResizeColumns="False" CanUserResizeRows="False" Margin="2,0" CanUserSortColumns="False" SelectionMode="Single" CanUserReorderColumns="False" CanUserAddRows="False" CanUserDeleteRows="False" HeadersVisibility="Column" GridLinesVisibility="All" AreRowDetailsFrozen="False" IsEnabled="True" CellEditEnding="DataGridMeterValues_CellEditEnding">
<DataGrid.Resources>
<Style x:Key="DataGridBase" TargetType="Control">
<Setter Property="LayoutTransform">
<Setter.Value>
<TransformGroup>
<RotateTransform Angle="-90" />
<ScaleTransform ScaleX="1" ScaleY="-1" />
</TransformGroup>
</Setter.Value>
</Setter>
<Setter Property="TextOptions.TextFormattingMode" Value="Display" />
</Style >
<Style TargetType="DataGridCell" BasedOn="{StaticResource DataGridBase}"/>
<Style TargetType="DataGridColumnHeader" BasedOn="{StaticResource DataGridBase}"/>
</DataGrid.Resources>
<DataGrid.LayoutTransform>
<TransformGroup>
<RotateTransform Angle="90" />
<MatrixTransform Matrix="-1, 0, 0, 1, 0, 0" />
</TransformGroup>
</DataGrid.LayoutTransform>
<DataGrid.RowHeaderStyle >
<Style TargetType="DataGridRowHeader">
<Setter Property="Content" Value="X" />
</Style>
</DataGrid.RowHeaderStyle>
<DataGrid.Columns>
<DataGridTemplateColumn Header="Action" >
<DataGridTemplateColumn.CellTemplate >
<DataTemplate>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
<Button Tag="{Binding}" Content="Activate" Width="50" BorderThickness="0" Margin="2" Background="{Binding Path=Activated}" Click="BtnActivate_Click" />
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn Header="Name" Binding="{Binding Path=Title, UpdateSourceTrigger=PropertyChanged}" />
<DataGridTextColumn Header="Meter Type" Binding="{Binding Path=Type, UpdateSourceTrigger=PropertyChanged}" />
</DataGrid.Columns>
</DataGrid>