【问题标题】:WPF ListView: Set the Background color for specific items when Focusable is set to falseWPF ListView:当 Focusable 设置为 false 时为特定项目设置背景颜色
【发布时间】:2016-01-20 16:36:31
【问题描述】:

基本上,我有一个 ListView 有两个条件:

  • 不要让用户选择任何项目(出于可用性原因)
  • 如果行满足特定条件,则显示具有特殊背景颜色的行

做这两点很容易,但我无法同时做到这两点。一个让解释更容易的例子:

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

如果我删除 ListView.ItemContainerStyle 部分,背景颜色绘制正确。但是当 Focusable 设置为 false 时,将 Background 设置为 LightGray 是没有效果的。

有没有办法同时做到这两点?

【问题讨论】:

  • 可能更容易使用像这样的项目模板stackoverflow.com/a/6174312/1328536
  • 项目模板可能是一种解决方法,是的。谢谢你的提示。不过,我希望能指出我的一些愚蠢的思维错误:)。我的意思是,默认行为正是我所需要的:我只想列出集合的每个项目并在列中显示不同的属性。到目前为止,它做得非常好。不知道制作这样一个通用的项目模板有多容易?

标签: c# wpf xaml


【解决方案1】:

使用您当前的代码,您实际上设置了两次样式,因此第二个样式声明将被忽略。摆脱 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>

【讨论】:

  • 哦。那是我希望的一些愚蠢的思维错误的指针;)。谢谢!
【解决方案2】:

看来您还需要一个触发器来解决“如果选择”的外观问题。类似的东西:

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

此外,您可能会发现此讨论也很有用:Change selection-color of WPF ListViewItem

【讨论】:

  • 谢谢,但我不确定这是否真的是我的问题的答案。因为它不是关于更改选定 ListView 项目的颜色,而是关于更改 unselectable ListVIew 项目的颜色:)。
  • 另一种选择:如果您尝试使用 而不是 会怎样?但是,请注意它缺少许多有用的功能。例如,如果需要滚动,则必须将其包装到 中。
  • 我认为 ItemsControl 的缺点太大 - 我宁愿删除没有 itams 可以选择的条件,而不是不使用 ListView。但感谢您的回答 - 他们也帮助了其他可能的情况。
猜你喜欢
  • 2014-03-21
  • 2015-04-19
  • 2019-09-01
  • 2011-08-28
  • 1970-01-01
  • 2011-10-26
  • 1970-01-01
  • 2016-08-10
  • 1970-01-01
相关资源
最近更新 更多