Style list item based on its property

2019-09-06 06:15发布

问题:

I am pretty new to WPF and I am trying to build a quite simple application using MVVM light.

In my MainWindow.xaml (view) I have this :

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

Where InstalledVersions is a list of InstalledVersionViewModel

In my MainWindowResources.xaml I have this (simplified) :

<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.

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 :

    <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 !

回答1:

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


标签: c# wpf xaml mvvm