C# WPF在列表框中选择时更改datatemplate的可视状态
如果我有一个WPFC# WPF在列表框中选择时更改datatemplate的可视状态,c#,wpf,listbox,visualstatemanager,C#,Wpf,Listbox,Visualstatemanager,如果我有一个WPF列表框,它有一个包含自定义用户控件的基本项模板,我如何告诉数据模板中的用户控件在列表框中选中时更改其视觉状态 非常感谢您提供的任何帮助您可以设置ListBoxItem的样式,以在IsSelected属性上触发。下面是一个例子: 然后你像这样使用它: <ListBox ItemContainerStyle="{StaticResource yourListBoxItemStyle}"> 编辑: 下面是一个完整的示例,其中包含一个ItemTemplate和一个I
列表框
,它有一个包含自定义用户控件的基本项模板
,我如何告诉数据模板
中的用户控件在列表框
中选中时更改其视觉状态
非常感谢您提供的任何帮助您可以设置
ListBoxItem
的样式,以在IsSelected
属性上触发。下面是一个例子:
<ListBox ItemContainerStyle="{StaticResource yourListBoxItemStyle}">
编辑:
下面是一个完整的示例,其中包含一个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>
那么你是说根本不要使用ItemTemplate吗?不,继续使用你的ItemTemplate
。示例中ControlTemplate
中的ContentPresenter
将最终“扩展”您的ItemTemplate
。好的,谢谢您的代码,但是如果我想更改控件的属性(在您的示例中是Rectangle类),我不知道这将如何工作在DataTemplate中,因为您无法从itemcontainer访问控件template@Mark:通常这些是分开的,因此选择逻辑不必在每个数据模板中重复。但是如果您想将两者结合起来,那么就用数据模板
替换ContentPresenter
,然后您就可以直接控制ListBoxItem
的内容了。这样的话,您就不会设置ItemTemplate了?
<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>