我有一个 ListBox,其中每个项目都是一个 StackPanel。 StackPanel 由一个 Image 和它下面的一个 TextBlock 组成:
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Margin="10">
<Image>
<Image.Source>
<BitmapImage UriSource="{Binding Path=ImageFilePath}"/>
</Image.Source>
</Image>
<TextBlock Text="Title" TextAlignment="Center"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
它看起来像这样:
当用户选择一个项目时,我会得到围绕 StackPanel 的默认蓝色矩形:
现在,我想为所选项目制作不同的边框,但我希望它仅围绕图像.
我知道如何制作控件模板并在 ContentPresenter 周围放置自定义边框,但这当然会围绕整个 StackPanel,而不仅仅是 Image。
我不知道是否可以对 ContentPresenter 进行更改,以及这是否是一个好主意。如果有其他方法可以达到我想要的外观,那也很好。
是的,ListBox 自己的 ContentPresenter 对您正在做的事情没有帮助。您想要 a) 消除 ListBox 自己的选择视觉效果,b) 将其替换为 DataTemplate 中更适合您的项目的内容。
默认选择视觉效果由默认模板应用ListBoxItem
。因此替换该模板。使用资源中的样式ListBox
,应用您自己的控件模板ListBoxItem
。内容不多,只是展示内容,不提供选择背景。然后,您可以使用数据模板中的触发器来处理选择视觉效果,其中定义了图像和标签,并且您可以将更改应用于其中之一,而不是另一个。下面的例子对我有用。
请注意,对 Border 元素上的 HorizontalAlignment 进行了一些调整,使其紧贴其中的 Image 元素。另外,我编写了一个快速测试视图模型,其 Items 属性称为Items
;我假设这不是您用来填充自己的列表框的集合成员的名称。
<ListBox
Margin="8"
ItemsSource="{Binding Items}"
>
<ListBox.Resources>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<Grid>
<ContentPresenter />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.Resources>
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Border
x:Name="HighlightBorder"
BorderThickness="4"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Margin="10"
>
<Border.Style>
<Style TargetType="Border">
<!-- MUST set default BorderBrush via a style, if you set it at all.
As an attribute on the Border tag, it would override the effects of
the trigger below.
-->
<Setter Property="BorderBrush" Value="Transparent" />
</Style>
</Border.Style>
<Image Source="{Binding ImageFilePath}" />
</Border>
</Grid>
<DataTemplate.Triggers>
<DataTrigger
Binding="{Binding IsSelected, RelativeSource={RelativeSource AncestorType=ListBoxItem}}"
Value="True">
<Setter TargetName="HighlightBorder" Property="BorderBrush" Value="Orange" />
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)