1

应用定义的隐式 DataGridCell 样式,而不是通过 DataGrid 的样式(DataGrid.CellStyle 属性)设置的显式样式。为什么?XAML 如何评估,在这种情况下是否使用隐式样式而不是显式样式?

我正在尝试创建 DataGrid 样式,它还将设置 DataGridCells 的样式。

尝试删除隐式 DataGridCell 样式,一切都按预期工作,显式样式正常工作。

如何让它们协同工作?

还提供 DataGridCell 样式作为 DataGrid 的样式资源。如何?为什么?

DataGridCell 的隐式样式

<!-- Implicit DataGridCell style -->
<Style TargetType="{x:Type DataGridCell}">
    <Setter Property="FontSize" Value="14" />
    <Setter Property="Background" Value="White" />
    <Setter Property="BorderBrush" Value="White" />
    <Style.Triggers>
       <Trigger Property="IsSelected" Value="True">
           <Setter Property="Background" Value="White" />
            <Setter Property="BorderBrush" Value="White" />
        </Trigger>
    </Style.Triggers>
</Style>

我要应用的 DataGridCell 的样式

<!-- Explicit DataGridCellStyle -->
<Style x:Key="DataGridCellStyle" TargetType="DataGridCell" BasedOn="{StaticResource {x:Type DataGridCell}}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type DataGridCell}">
                <Border BorderBrush="{TemplateBinding BorderBrush}"
                        BorderThickness="{TemplateBinding BorderThickness}"
                        Background="{TemplateBinding Background}" SnapsToDevicePixels="True">
                    <ContentPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" />
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>

    <Style.Triggers>
        <Trigger Property="IsSelected" Value="True">
            <Setter Property="BorderThickness" Value="0" />
            <Setter Property="Foreground" Value="#ffffff" />
            <Setter Property="Background">
                <Setter.Value>
                    <LinearGradientBrush EndPoint="0.5,1"
                                         MappingMode="RelativeToBoundingBox" StartPoint="0.5,0">
                        <GradientStop Color="#FF3b85c8" Offset="0" />
                        <GradientStop Color="#FF0668b7" Offset="1" />
                    </LinearGradientBrush>
                </Setter.Value>
            </Setter>
        </Trigger>

    </Style.Triggers>
</Style>

数据网格的样式

<!-- DataGrid style -->
<Style x:Key="BaseDataGrid" TargetType="{x:Type DataGrid}">
    <Setter Property="CellStyle" Value="{StaticResource DataGridCellStyle}" />

    <!-- Uncommenting this makes the solution works even with Implicit style -->
    <!--<Style.Resources>
        <Style TargetType="{x:Type DataGridCell}" BasedOn="{StaticResource DataGridCellStyle}"/>
    </Style.Resources>-->

</Style>

简单的 Datagrid 实例

<!-- Data grid itself -->
<DataGrid Style="{StaticResource BaseDataGrid}"
          AutoGenerateColumns="True"
          ItemsSource="{Binding ModelClasses}">
</DataGrid>
4

0 回答 0