且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

DataGrid选定的单元格背景

更新时间:2022-12-28 17:21:41

如果要更改 DataGridCell.Background 属性,则需要在 ControlTemplate 中使用它>

例如使用 TemplateBinding

 <边框名称="DataGridCellBorder"Background ="{TemplateBinding Background}"/> 

I'm having trouble with the WPF DataGrid.

I have the following code..

<Style TargetType="{x:Type DataGridCell}">
       <Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self}, Path=Content.Text}" />
       <Setter Property="Template">
          <Setter.Value>
            <ControlTemplate TargetType="{x:Type DataGridCell}">
            <Border Name="DataGridCellBorder">
            <ContentControl Content="{TemplateBinding Content}">
             <ContentControl.ContentTemplate>
                <DataTemplate>
                   <TextBlock
                      Width="auto"
                      Height="auto"
                      Background="Transparent"
                      Text="{Binding Text}"
                      TextTrimming="CharacterEllipsis"
                      TextWrapping="WrapWithOverflow" />
                        </DataTemplate>
                     </ContentControl.ContentTemplate>
                  </ContentControl>
               </Border>
               <ControlTemplate.Triggers>
                <Trigger Property="IsSelected" Value="True">
                    <Setter Property="Background" Value="Orange" />
                </Trigger>
               </ControlTemplate.Triggers>
            </ControlTemplate>
          </Setter.Value>
       </Setter>
    </Style>

As you can see, I have replaced the default DataGridCell with a custom template. This was needed as I wanted the cells to have TextTrimming if the text was too big to fit in to the given cell (this is fully shown in the ToolTip when the user hovers over a given cell)

My problem now is that when I select a cell, the foreground get's set to White no matter what I try and do - What I really want to happen is have the cells (or even better, the complete row) background colour change to Orange.

Any help with this would be great

Kris

If you are going to change the DataGridCell.Background property you need to use it somewhere in your ControlTemplate

e.g. using a TemplateBinding

<Border Name="DataGridCellBorder"
        Background="{TemplateBinding Background}"/>