【发布时间】:2011-01-19 16:01:39
【问题描述】:
如何在DataGrid 的一列上设置自定义网格线样式?特别是,我希望一列有一条双线作为其左边框。
例子:
| Col1 | Col2 || Col3 (w/ Double Left Border) |
谢谢你,
本
【问题讨论】:
如何在DataGrid 的一列上设置自定义网格线样式?特别是,我希望一列有一条双线作为其左边框。
例子:
| Col1 | Col2 || Col3 (w/ Double Left Border) |
谢谢你,
本
【问题讨论】:
这取决于你想要这条双线的位置。垂直网格线在OnRender 中绘制为DataGridCell,水平网格线在OnRender 中绘制为DataGridCellsPresenter。但是,DataGridColumnHeader 的边框更复杂。这是一个在DataGridHeaderBorder 中的RenderTheme 方法中绘制的矩形,我认为没有直接的方法可以在不重新模板化整个DataGridColumnHeader 的情况下更改其宽度。此外,Headers 的边框厚度是 DataGrid 中单元格的两倍粗(1px vs 2px),因为 Headers 在两侧都绘制了它们的分隔符。
因此,要获得仅影响单元格的双线粗细,您可以添加特殊的DataGridCell 样式以应用此样式。这个单元格样式所做的就是在左侧绘制一个与 GridLines 相同颜色的 1px 边框。它看起来像这样
<DataGrid ...
HorizontalGridLinesBrush="Black">
<DataGrid.Resources>
<Style x:Key="DoubleLeftBorderCell" TargetType="DataGridCell">
<Setter Property="BorderThickness" Value="1,0,0,0"/>
<Setter Property="BorderBrush" Value="{Binding ElementName=dataGrid, Path=HorizontalGridLinesBrush}"/>
</Style>
</DataGrid.Resources>
<DataGrid.Columns>
<DataGridTextColumn Header="Double left Border"
CellStyle="{StaticResource DoubleLeftBorderCell}"
Binding="{Binding TextProperty}"/>
</DataGrid.Columns>
</DataGrid>
没有鼠标悬停效果或任何需要担心的单元格。但是,如果您对 DataGridColumnHeader 执行类似操作,您将失去排序箭头、鼠标悬停效果、鼠标按下效果等,因此您必须为它创建一个完整的模板
【讨论】:
这是我最终做的:
<DataGridTextColumn Header="Header Name">
<DataGridTextColumn.CellStyle>
<Style TargetType="{x:Type DataGridCell}">
<Setter Property="Margin" Value="1 0 0 0" />
<Setter Property="BorderThickness" Value="1 0 0 0" />
<Setter Property="BorderBrush" Value="{Binding RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}, Path=HorizontalGridLinesBrush}" />
</Style>
</DataGridTextColumn.CellStyle>
</DataGridTextColumn>
这基于 Meleak 的回答,但添加了边距(以创建双线效果)并使用 RelativeSource 作为边框画笔,从而消除了 DataGrid 具有 x:Name 的需要。
【讨论】: