我想在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-23 03:51:57
查看样式的"BasedOn“属性...
例如,下面的样式从DataGridColumnHeader获取所有内容,并且只覆盖HorizontalContentAlignment属性:
<Style x:Key="CenterAlignedColumnHeaderStyle" TargetType="{x:Type DataGridColumnHeader}"
BasedOn="{StaticResource {x:Type DataGridColumnHeader}}">
<Setter Property="HorizontalContentAlignment" Value="Center"/>
</Style>发布于 2011-12-22 04:18:06
在WPF中重写控件模板需要完全替换模板。您可能只想更改模板的一个方面,但其结果是表达式转储模板的其余部分的副本,以便它可以被覆盖。确保以正确的方式重写单元格(我不确定是否还有其他方法)。有些控件(我想到的是ListView)可以让您在不覆盖整个控件模板的情况下交换数据模板,但我不确定这是否是您想要的,或者是否可以用DataGrid完成。
发布于 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
复制相似问题