WPF DataGrid DataGridRow选择边框和间距

时间:2015-04-24 17:29:49

标签: wpf datagrid border datatrigger

我正在使用WPF DataGrid显示数据,当用户选择一行时,我希望整个行的背景突出显示(使用渐变)并且还有边框。我一直在使用以下代码,它在很大程度上起作用:

    <Style TargetType="DataGridRow">
        <Setter Property="BorderBrush" Value="Transparent" />
        <Setter Property="BorderThickness" Value="0" />
    <Style.Triggers>
        <DataTrigger Binding="{Binding IsChecked}" Value="True">
            <Setter Property="BorderThickness" Value="1"/>
            <Setter Property="BorderBrush" Value="{StaticResource BorderColor}" />
            <Setter Property="Background" Value="{StaticResource BackgroundColor}" />
        </DataTrigger>
    </Style.Triggers>
    </Style>

我遇到的这个问题与边界有关。如果BorderThickness最初设置为0,则整个Row“切换”以在触发DataTrigger时为边框腾出空间。如果我最初将BorderThickness设置为1,则突出显示的行会正确显示,但当行处于默认状态时,行周围会有一个空边框,导致行网格线不会触及边缘。

关于如何解决这个问题的任何想法?

1 个答案:

答案 0 :(得分:0)

我发现使用ListBox代替DataGrid可以更轻松地调整视觉效果,所以这可能是一种方法。

以此为出发点:

<ListBox>
    <ListBox.ItemContainerStyle>
        <Style TargetType="{x:Type ListBoxItem}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding IsChecked}" Value="True">
                    <Setter Property="BorderBrush" Value="{StaticResource BorderColor}" />
                    <Setter Property="Background" Value="{StaticResource BackgroundColor}" />
                </DataTrigger>
            </Style.Triggers>
            <Setter Property="Background" Value="Transparent" />
            <Setter Property="BorderBrush" Value="Transparent" />
        </Style>
    </ListBox.ItemContainerStyle>
    <ListBox.ItemTemplate>
        <DataTemplate DataType="{x:Type local:MyClass}">
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="30" />
                    <ColumnDefinition Width="*" />
                </Grid.ColumnDefinitions>
                <CheckBox IsChecked="{Binding IsChecked}" />
                <TextBlock Text="{Binding MyTextProperty}" Grid.Column="1" />
            </Grid>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

这应该设置正确的边框和背景,而不移动所选行的元素或显示未选择的行的周围间隙。 只需将local:MyClass替换为您的类,并为您的场景自定义Grid内容。

请参阅this answer有关如何处理MouseOver / Selected样式的信息,我尝试将模板属性setter复制到上面的示例中,并调整Panel.Background和Border.BorderBrush setter,它们似乎运行良好。