0

我有覆盖DataGrid。下面是我的代码和 XAML。选择单元格时如何设置样式以更改DataGridCell背景颜色?

<vw:DataGridExt 
   Grid.Row="1" 
   AlternatingRowBackground="LightGray" 
   ItemsSource="{Binding RelativeSource={RelativeSource TemplatedParent},Path=Value,Mode=OneWay, IsAsync=True}" 
   Background="White" 
   AutoGenerateColumns="True" 
   IsReadOnly="True" 
   CanUserResizeRows="False" 
   ClipboardCopyMode="IncludeHeader"
   CanUserSortColumns="True" 
   CanUserAddRows="False" 
   SelectionMode="Extended"/>                 

 public class DataGridExt : DataGrid
 {
     public DataGridExt()
     {
         this.AutoGeneratedColumns += new EventHandler(DataGrid_AutoGeneratedColumns);
     }
 }
4

1 回答 1

0

您必须为 DataGridCell 提供样式

<Style TargetType="{x:Type DataGridCell}">   
  <Setter Property="Background" Value="Transparent" />        
    <Setter Property="BorderThickness" Value="1"/>
    <Setter Property="BorderBrush" Value="Transparent"/>     
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type DataGridCell}">
                <Border Background="{TemplateBinding Background}" 
                        BorderBrush="{TemplateBinding BorderBrush}"  
                        BorderThickness="{TemplateBinding BorderThickness}" >
                    <ContentPresenter />
                </Border>                              
            </ControlTemplate>
        </Setter.Value>
    </Setter>
    <Style.Triggers>
        <Trigger Property="IsKeyboardFocusWithin" Value="True">
            <Setter Property="BorderBrush" Value="Black" />
        </Trigger>
        <Trigger Property="IsSelected" Value="True">
            <Setter Property="Background" Value="Gray"/>
        </Trigger>
    </Style.Triggers>
</Style>

并设置

SelectionUnit="Cell" for your DataGrid.

希望能帮助到你。

于 2013-07-14T17:12:57.880 回答