首页 > 解决方案 > 如何在 WPF 中的 ListBox 边框上绘制 ListBoxItem 边框?

问题描述

我想设计一个ListBox看起来就像所选项目在ListBox. ListBox有一个 1px 的边框。为true时ListBoxItem有边框"0 0 0 1"和高亮颜色。IsSelected

当一个项目被选中时,它的右边的边框应该被绘制在ListBox.

这是一张图片,展示了它的外观:

在此处输入图像描述

我尝试使用 and 的边距,ListBox但是ListBoxItemListBoxItem到达ListBox.

有没有办法ListBoxItemsListBox's 的边界上绘制边界?

标签: wpf

解决方案


您可以重新模板化ListBox(以更好地控制边距等)和基于属性ListBoxItem定义的。BorderBrushIsSelected

"它右边的边界应该画在边界上ListBox"

好吧,您可以通过完全Border没有ListBox. 你可以让每个ListBoxItem人对它的正确Border颜色负责。ListBox本身看起来像这样,没有权利Border

没有右边框的列表框

现在您只需要Border在每个ListBoxItem.

我最终Margin="1 0 0 0"在内部添加了一个调整,ItemsPresenter使整体外观更平滑。

<ListBox HorizontalAlignment="Left"
         VerticalAlignment="Top"
         Background="LightGray"
         BorderThickness="5 5 0 5"
         BorderBrush="Black">
    <ListBox.Template>
        <ControlTemplate TargetType="ListBox">
            <Border BorderThickness="{TemplateBinding BorderThickness}"
                    BorderBrush="{TemplateBinding BorderBrush}"
                    Background="{TemplateBinding Background}">
                <ItemsPresenter Margin="1 0 0 0"/>
            </Border>
        </ControlTemplate>
    </ListBox.Template>
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="ListBoxItem">
                        <Border BorderThickness="0 0 5 0" Padding="5">
                            <ContentPresenter/>
                            <Border.Style>
                                <Style TargetType="Border">
                                    <Setter Property="BorderBrush" Value="Black"/>
                                    <Style.Triggers>
                                        <DataTrigger Binding="{Binding Path=IsSelected, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ListBoxItem}}" Value="True">
                                            <Setter Property="BorderBrush" Value="Blue"/>
                                            <Setter Property="Control.Foreground" Value="Blue"/>
                                        </DataTrigger>
                                    </Style.Triggers>
                                </Style>
                            </Border.Style>
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </ListBox.ItemContainerStyle>
    <ListBoxItem Content="Item1"/>
    <ListBoxItem Content="Item2"/>
    <ListBoxItem Content="Item3"/>
</ListBox>

最后的样子:

所选中间元素的屏幕截图

您必须添加大量样式才能获得完整的结果,但这是您可以采用的一种方式。


推荐阅读