应用了定义的隐式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的样式
<!-- 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>