我想在WPF中编辑一个DataGrid的单元格样式。所以使用Expression Blend我可以转到- Objects Timeline>>DataGrid>>Edit Additional Templates>>Edit CellStyle>>Edit a Copy
以下是页面上显示的内容:
<SolidColorBrush x:Key="{x:Static DataGrid.FocusBorderBrushKey}" Color="#FF000000"/>
<Style x:Key="DataGridCellStyle1" TargetType="{x:Type DataGridCell}">
<Setter Property="Background" Value="Transparent"/>
<Setter Property="BorderBrush" Value="Transparent"/>
<Setter Property="BorderThickness" Value="1"/>
<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="Background" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/>
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.HighlightTextBrushKey}}"/>
<Setter Property="BorderBrush" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/>
</Trigger>
<Trigger Property="IsKeyboardFocusWithin" Value="True">
<Setter Property="BorderBrush" Value="{DynamicResource {x:Static DataGrid.FocusBorderBrushKey}}"/>
</Trigger>
</Style.Triggers>
</Style>但我只想改变填充和背景。相反,它给了我25行代码,包括单元格模板!我是否遗漏了什么,当我只想更改两个项目时,有没有更好的方法来样式化这样的项目,而不需要带来这么多额外的不必要的代码?
发布于 2011-12-22 08:35:16
要做想做的事情,通常只需在样式中设置背景和填充属性:
<Style TargetType="DataGridCell">
<Setter Property="Padding" Value="10" />
<Setter Property="Background" Value="Green" />
</Style>然而,在这种情况下,DataGridCell的默认控件模板似乎忽略了填充值,因此您需要将其替换为不会忽略填充值的实现。
<Style TargetType="DataGridCell">
<Setter Property="Padding" Value="10" />
<Setter Property="Background" Value="Green" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type DataGridCell}">
<Border BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
Background="{TemplateBinding Background}"
SnapsToDevicePixels="True">
<ContentPresenter
Margin="{TemplateBinding Padding}" <!-- this bit does the padding -->
SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>https://stackoverflow.com/questions/8594863
复制相似问题