简体   繁体   English

选择并聚焦时如何更改数据网格单元格背景颜色?

[英]How is it possible to change datagrid cell background color when is selected and focused?

I'm trying to change the Background property for the currently selected cell when I double clicked it, but since I'm new to WPF I got some issues.当我双击它时,我试图更改当前选定单元格的Background属性,但由于我是 WPF 的新手,因此遇到了一些问题。 I have tried this way with XAML:我已经用 XAML 尝试过这种方式:

<DataGrid.CellStyle>
   <Style TargetType="DataGridCell">
      <Style.Triggers>
         <Trigger Property="IsFocused" Value="True">
            <Setter Property="Background" Value="#FF333333"/>
         </Trigger>
      </Style.Triggers>
   </Style>
</DataGrid.CellStyle>

And programmatically:并以编程方式:

private void DataMapping_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
   var row = sender as DataGridRow;
   row.Background = new SolidColorBrush(Color.FromRgb(51, 51, 51));
}

双击时的单元格样式

Any suggestions?有什么建议? Full code for the Datagrid here. Datagrid 的完整代码在这里。

You have to create and set an EditingElementStyle for your data grid column, because you are in edit-mode when you double click a cell.您必须为数据网格列创建和设置EditingElementStyle ,因为双击单元格时您处于编辑模式 In that mode, the data grid cell contains specific controls for editing, like a TextBox for text columns, so changing the cell background will not have an effect.在该模式下,数据网格单元格包含用于编辑的特定控件,例如用于文本列的TextBox ,因此更改单元格背景不会产生影响。

The editing style below sets the Background and Foreground of the TextBox in edit-mode.下面的编辑样式在编辑模式下设置TextBoxBackgroundForeground

<DataGrid AutoGenerateColumns="False" ItemsSource="{Binding DataGridRows}" ...>
   <DataGrid.Resources>
      <!-- ...other data grid resources. -->
      <Style x:Key="DataGridTextColumnEditingStyle" 
             TargetType="{x:Type TextBox}"
             BasedOn="{StaticResource {x:Type TextBox}}">
         <Setter Property="Background" Value="#FF333333"/>
         <Setter Property="Foreground" Value="White"/>
      </Style>
   </DataGrid.Resources>
   <!-- ...other data grid code. -->
   <DataGrid.Columns>
      <!-- ...other data grid columns -->
      <DataGridTextColumn Header="CSV Column"
                          IsReadOnly="False"
                          Binding="{Binding Path=CSVColumnValue}"
                          Width="*"
                          Foreground="White"
                          EditingElementStyle="{StaticResource DataGridTextColumnEditingStyle}"/>
   </DataGrid.Columns>
</DataGrid>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM