根据其属性样式列表项(Style list item based on its property)

2019-10-20 07:33发布

我是很新的WPF,我试图建立使用MVVM光一个非常简单的应用程序。

在我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>

谢谢 !

Answer 1:

由于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>


文章来源: Style list item based on its property
标签: c# wpf xaml mvvm