【问题标题】:How is it possible to change datagrid cell background color when is selected and focused?选择并聚焦时如何更改数据网格单元格背景颜色?
【发布时间】:2020-08-26 10:37:15
【问题描述】:

当我双击它时,我正在尝试更改当前选定单元格的Background 属性,但由于我是 WPF 新手,我遇到了一些问题。我已经用 XAML 尝试过这种方式:

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

并以编程方式:

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

有什么建议吗? Full code for the Datagrid here.

【问题讨论】:

    标签: c# wpf datagrid


    【解决方案1】:

    您必须为您的数据网格列创建和设置EditingElementStyle,因为当您双击一个单元格时,您处于编辑模式。在该模式下,数据网格单元格包含用于编辑的特定控件,例如用于文本列的 TextBox,因此更改单元格背景不会产生影响。

    下面的编辑风格将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>
    

    【讨论】:

      猜你喜欢
      • 2015-10-09
      • 1970-01-01
      • 2011-12-23
      • 1970-01-01
      • 2013-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多