简体   繁体   English

基于样式列表项的属性

[英]Style list item based on its property

I am pretty new to WPF and I am trying to build a quite simple application using MVVM light. 我对WPF还是很陌生,我正在尝试使用MVVM light构建一个非常简单的应用程序。

In my MainWindow.xaml (view) I have this : 在我的MainWindow.xaml(视图)中,我有这个:

    <ListBox ItemsSource="{Binding InstalledVersions}"
             ItemTemplate="{StaticResource VersionsDataTemplate}"
             Style="{StaticResource VersionsStyle}"
             ItemContainerStyle="{StaticResource VersionItemStyle}"/>

Where InstalledVersions is a list of InstalledVersionViewModel 其中InstalledVersions是InstalledVersionViewModel的列表

In my MainWindowResources.xaml I have this (simplified) : 在我的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>

I wish to have a different background depending on the "IsActive" property of my InstalledVersionViewModel. 我希望具有不同的背景,具体取决于我的InstalledVersionViewModel的“ IsActive”属性。

I tried to add this (as well as several variations of it) to my VersionItemStyle but (as I suspected, mostly because I don't understand what I'm doing) it doesn't work : 我试图将它(以及它的几个变体)添加到我的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>

Thanks ! 谢谢 !

Since IsActive is part of view model against each row you can achieve that with DataTrigger 由于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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM