wpf - 如何在 WPF 中的 ListBox 边框上绘制 ListBoxItem 边框?
问题描述
我想设计一个ListBox
看起来就像所选项目在ListBox
. ListBox
有一个 1px 的边框。为true时ListBoxItem
有边框"0 0 0 1"
和高亮颜色。IsSelected
当一个项目被选中时,它的右边的边框应该被绘制在ListBox
.
这是一张图片,展示了它的外观:
我尝试使用 and 的边距,ListBox
但是ListBoxItem
当ListBoxItem
到达ListBox
.
有没有办法ListBoxItems
在ListBox
's 的边界上绘制边界?
解决方案
您可以重新模板化ListBox
(以更好地控制边距等)和基于属性ListBoxItem
定义的。BorderBrush
IsSelected
"它右边的边界应该画在边界上
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>
最后的样子:
您必须添加大量样式才能获得完整的结果,但这是您可以采用的一种方式。
推荐阅读
- python - pywintypes.com_error:(-2147221008,'CoInitialize 尚未被调用。',无,无)
- ruby-on-rails - 为什么在尝试获取嵌套 JSON 属性时出现“没有将字符串隐式转换为整数”?
- php - 如何优化 api 性能
- python - 使用 Python 从 URL 导入数据(到 pandas 数据框)?
- python - 转换日期时间以允许减法
- django - MOD_WSGI Apache2 您无权访问此资源
- matlab - 在 MATLAB 中在 [-2,7] 上绘制函数符号
- c# - ListView 的句柄 (x:Name) 在后面的代码中为空。Intellisense 在编码时“看到”句柄
- java - 数组继续在拦截器中添加相同的值
- javascript - 'this' 在函数中未定义