简体   繁体   English

WPF ListView:当Focusable设置为false时,为特定项目设置背景色

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

Basically, I have a ListView with two conditions: 基本上,我有两个条件的ListView:

  • 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. 如果删除ListView.ItemContainerStyle零件,则背景颜色将正确绘制。 But when Focusable is set to false, setting the Background to LightGray has no effect. 但是,当Focusable设置为false时,将Background设置为LightGray无效。

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: 摆脱ItemContainerStyle并将您的Focusable属性移至第二种样式,如下所示:

<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 此外,您可能还会发现此讨论也有用: 更改WPF ListViewItem的选择颜色

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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