如果我有一个包含自定义用户控件ListBox
的基本 WPF,ItemTemplate
我如何告诉用户控件在 中DataTemplate
选择它时更改其视觉状态ListBox
?
非常感谢您提供的任何帮助
如果我有一个包含自定义用户控件ListBox
的基本 WPF,ItemTemplate
我如何告诉用户控件在 中DataTemplate
选择它时更改其视觉状态ListBox
?
非常感谢您提供的任何帮助
您可以在属性上设置ListBoxItem
要触发的样式。IsSelected
这是一个例子:
然后你像这样使用它:
<ListBox ItemContainerStyle="{StaticResource yourListBoxItemStyle}">
或直接在其ListBox
本身:
<ListBox.ItemContainerStyle>
<Style TargetType=”ListBoxItem”>
...
</Style>
</ListBox.ItemContainerStyle>
编辑:
这是一个完整的示例,其中包含 anItemTemplate
和 an ItemContainerStyle
,它在所选项目的顶部放置了一个半透明层。
<Grid>
<Grid.Resources>
<x:Array Type="sys:String" x:Key="sampleData">
<sys:String>Red</sys:String>
<sys:String>Green</sys:String>
<sys:String>Blue</sys:String>
</x:Array>
<DataTemplate x:Key="listBoxItem">
<Rectangle Fill="{Binding}" Width="100" Height="100"/>
</DataTemplate>
<Style TargetType="ListBoxItem" x:Key="listBoxItemStyle">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<Grid>
<ContentPresenter />
<Rectangle x:Name="Rectangle" Fill="Black" Opacity="0"/>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="true">
<Setter TargetName="Rectangle" Property="Opacity"
Value="0.5"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Grid.Resources>
<ListBox
ItemsSource="{StaticResource sampleData}"
ItemTemplate="{StaticResource listBoxItem}"
ItemContainerStyle="{StaticResource listBoxItemStyle}"
/>
</Grid>
编辑
评论后,这里是使用“统一”模板的版本:
<Style TargetType="ListBoxItem" x:Key="listBoxItemStyle">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<Grid>
<Rectangle Name="Rectangle" Fill="{Binding}" Width="100" Height="100" Opacity="1"/>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="true">
<Setter TargetName="Rectangle" Property="Opacity"
Value="0.5"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>