[英]Style list item based on its property
我对WPF还是很陌生,我正在尝试使用MVVM light构建一个非常简单的应用程序。
在我的MainWindow.xaml(视图)中,我有这个:
<ListBox ItemsSource="{Binding InstalledVersions}"
ItemTemplate="{StaticResource VersionsDataTemplate}"
Style="{StaticResource VersionsStyle}"
ItemContainerStyle="{StaticResource VersionItemStyle}"/>
其中InstalledVersions是InstalledVersionViewModel的列表
在我的MainWindowResources.xaml中,我有这个(简体):
<DataTemplate x:Key="VersionsDataTemplate"
DataType="{x:Type viewmodels:InstalledVersionViewModel}">
<Grid>
<TextBlock Text="{Binding VersionNumber}" />
<TextBlock Text="{Binding FolderPath}" />
</Grid>
</DataTemplate>
<Style x:Key="VersionsStyle"
TargetType="{x:Type ListBox}">
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
<Setter Property="VerticalContentAlignment" Value="Center" />
</Style>
<Style x:Key="VersionItemStyle"
TargetType="{x:Type ListBoxItem}">
<Setter Property="Background" Value="White" />
</Style>
我希望具有不同的背景,具体取决于我的InstalledVersionViewModel的“ IsActive”属性。
我试图将它(以及它的几个变体)添加到我的VersionItemStyle中,但是(据我怀疑,主要是因为我不了解自己在做什么),它不起作用:
<Style.Triggers>
<Trigger Property="{Binding Path=DataContext.IsActive, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type viewmodels:InstalledVersionViewModel}}}" Value="True">
<Setter Property="Background" Value="Red" />
</Trigger>
</Style.Triggers>
谢谢 !
由于IsActive
是每行视图模型的一部分,因此可以使用DataTrigger
实现
<Style x:Key="VersionItemStyle" TargetType="{x:Type ListBoxItem}">
<Setter Property="Background" Value="White" />
<Style.Triggers>
<DataTrigger Binding="{Binding IsActive}" Value="True">
<Setter Property="Background" Value="Red" />
</DataTrigger>
</Style.Triggers>
</Style>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.