简体   繁体   中英

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.

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 !

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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