如果我有一个 WPF ListBox
它有一个基本的 ItemTemplate
包含自定义用户控件,我如何告诉 DataTemplate
中的用户控件在 ListBox
中选择时更改其视觉状态?
非常感谢您提供的任何帮助
最佳答案
您可以设置 ListBoxItem
的样式以触发 IsSelected
属性。这是一个例子:
然后你像这样使用它:
<ListBox ItemContainerStyle="{StaticResource yourListBoxItemStyle}">
或直接在 ListBox
本身中:
<ListBox.ItemContainerStyle>
<Style TargetType=”ListBoxItem”>
...
</Style>
</ListBox.ItemContainerStyle>
编辑:
这是一个完整的示例,其中包含一个 ItemTemplate
和一个 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>
关于c# - WPF 在列表框中选择时更改数据模板的视觉状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4622486/