如何在WPF中的DataGrid标题下绘制分隔线

时间:2017-11-06 12:16:45

标签: wpf xaml wpfdatagrid

有没有办法在DataGrid中的标题下面绘制分隔线?我已将GridLinesVisibility设置为None,因为除了标题下方的网格线之外我不想要任何网格线。我正在努力寻找一种方法来做到这一点,任何帮助将不胜感激。

这就是我想要实现的目标。

enter image description here

1 个答案:

答案 0 :(得分:2)

您可以修改DataGridColumnHeader' ControlTemplate

我使用了原始的DataGrid模板并替换了默认边框,并使用高度为1的Rectangle填充。

<DataGrid>
    <DataGrid.ColumnHeaderStyle>
        <Style TargetType="DataGridColumnHeader">
            <Style.Resources>

                <!-- This style is required for the column resize thumbs -->
                <Style x:Key="ColumnHeaderGripperStyle" TargetType="{x:Type Thumb}">
                    <Setter Property="Width" Value="8" />
                    <Setter Property="Background" Value="Transparent" />
                    <Setter Property="Cursor" Value="SizeWE" />
                    <Setter Property="Template">
                        <Setter.Value>
                            <ControlTemplate TargetType="{x:Type Thumb}">
                                <Border Background="{TemplateBinding Background}" Padding="{TemplateBinding Padding}" />
                            </ControlTemplate>
                        </Setter.Value>
                    </Setter>
                </Style>
            </Style.Resources>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type DataGridColumnHeader}">
                        <Grid Background="White">
                            <Grid.RowDefinitions>
                                <RowDefinition/>
                                <RowDefinition Height="1"/>
                            </Grid.RowDefinitions>
                            <ContentPresenter Grid.Row="0" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                                                  SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"
                                                  VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />

                            <Thumb Grid.Row="0" x:Name="PART_LeftHeaderGripper" HorizontalAlignment="Left" Style="{StaticResource ColumnHeaderGripperStyle}" />
                            <Thumb Grid.Row="0" x:Name="PART_RightHeaderGripper" HorizontalAlignment="Right" Style="{StaticResource ColumnHeaderGripperStyle}" />

                            <Rectangle Grid.Row="1" Height="1" HorizontalAlignment="Stretch" Stroke="Black"/>
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </DataGrid.ColumnHeaderStyle>
</DataGrid>