【问题标题】:WPF DataGrid DataGridRow Selection Border and SpacingWPF DataGrid DataGridRow 选择边框和间距
【发布时间】:2015-07-03 10:26:00
【问题描述】:

我正在使用 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,则在触发 DataTrigger 时,整个 Row 都会“移动”以为边框腾出空间。如果我最初将 BorderThickness 设置为 1,则突出显示的 Row 会正确显示,但是当 Row 处于默认状态时,它周围有一个空边框,导致 Row 网格线不接触边缘。

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

【问题讨论】:

    标签: wpf datagrid border datatrigger


    【解决方案1】:

    我发现使用 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 替换为您的类并为您的场景自定义网格内容。

    请参阅this answer 了解如何处理 MouseOver/Selected 样式,我尝试将模板属性设置器复制到我上面的示例中并调整 Panel.Background 和 Border.BorderBrush 设置器,这似乎运作良好。

    【讨论】:

    • 我什至没有想过尝试其他控件。感谢您的帮助!
    猜你喜欢
    • 2021-08-27
    • 1970-01-01
    • 2011-10-25
    • 2023-04-08
    • 2017-10-29
    • 1970-01-01
    • 2014-07-25
    • 1970-01-01
    • 2018-08-03
    相关资源
    最近更新 更多