2

如何在DataGrid的一列上设置自定义网格线样式?特别是,我希望一列有一条双线作为其左边框。

例子:

| Col1 | Col2 || Col3 (w/ Double Left Border) |

谢谢你,

4

2 回答 2

4

这取决于您想要这条双线的位置。垂直 GridLines 绘制在OnRenderfor 中DataGridCell,水平 GridLines 绘制在OnRenderfor 中DataGridCellsPresenter。然而,边界DataGridColumnHeader更复杂。RenderTheme这是一个在方法中绘制的 Rectangle,DataGridHeaderBorder我认为没有直接的方法可以在不重新模板化整个DataGridColumnHeader. 此外,Headers 的边框厚度是开始时 Cells 的两倍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>

没有鼠标悬停效果或任何需要担心的单元格。但是,如果您对 a 执行类似操作DataGridColumnHeader,您将失去排序箭头、鼠标悬停效果、鼠标按下效果等,因此您必须为它创建一个完整的模板

于 2011-01-19T22:59:29.553 回答
2

这就是我最终做的事情:

<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 具有 ax:Name 的需要。

于 2011-01-20T16:29:26.260 回答