简体   繁体   中英

WPF ListView: Set the Background color for specific items when Focusable is set to false

Basically, I have a ListView with two conditions:

  • Don't let the user select any items (for usability reason)
  • Display rows with a special background color if they fulfill a certain condition

Doing either of the points is easy, but I don't manage to do both at the same time. An example to make explanations easier:

<ListView ItemsSource="{Binding Items}">
    <ListView.ItemContainerStyle>
        <Style TargetType="ListViewItem">
            <Setter Property="Focusable" Value="false"/>
        </Style>
    </ListView.ItemContainerStyle>
    <ListView.Resources>
        <Style TargetType="{x:Type ListViewItem}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding IsOnline}" Value="false">
                    <Setter Property="Background" Value="LightGray" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </ListView.Resources>
    [... the rest ...]
</ListView>

If I remove the ListView.ItemContainerStyle part, the background colors are drawn correctly. But when Focusable is set to false, setting the Background to LightGray has no effect.

Is there a way to do both at the same time?

With your current code you are effectively setting the style twice, so the second style declaration is being ignored. Get rid of the ItemContainerStyle and move your Focusable property into the second style as below:

<ListView ItemsSource="{Binding Items}">
<ListView.Resources>
    <Style TargetType="{x:Type ListViewItem}">
    <Setter Property="Focusable" Value="false"/>
        <Style.Triggers>
            <DataTrigger Binding="{Binding IsOnline}" Value="false">
                <Setter Property="Background" Value="LightGray" />
            </DataTrigger>
        </Style.Triggers>
    </Style>
</ListView.Resources>
[... the rest ...]
</ListView>

It seems you need one more trigger to address "if selected" appearance. Something like that:

<Style.Triggers>
    <DataTrigger Binding="{Binding Path=IsSelected, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ListViewItem}}}" Value="True">
        <Setter Property="Background" Value="place a color you want">
    </DataTrigger>
</Style.Triggers>

Also, you may find this discussion usefull too: Change selection-color of WPF ListViewItem

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