【问题标题】:ListView SelectedItem Alternating Background ColorListView SelectedItem 交替背景颜色
【发布时间】:2011-10-13 23:05:48
【问题描述】:

我在 ListView 上使用(3.5 版的新功能)AlternationIndex 触发器来应用这样的交替背景颜色:

<ListView.ItemContainerStyle>
    <Style TargetType="{x:Type ListViewItem}">
        <Setter Property="HorizontalContentAlignment" Value="Stretch" />
        <Style.Triggers>
            <Trigger Property="ItemsControl.AlternationIndex" Value="0">
                <Setter Property="Background" Value="White" />
            </Trigger>
            <Trigger Property="ItemsControl.AlternationIndex" Value="1">
                <Setter Property="Background" Value="#300761AE" />
            </Trigger>
        </Style.Triggers>
    </Style>
</ListView.ItemContainerStyle>

这部分效果很好,ListView 看起来完全符合我的要求。我唯一的问题是 SelectedItem 的背景颜色。对于我的列表,实际上无法选择项目,因为从上下文来看这是没有意义的。我想要找到的是一种让 SelectedItem 的背景颜色变为空的方法,这样父 ListViewItem 的颜色就会发光。透明不起作用,因为这基本上等同于白色,并且当我使用透明时交替样式消失了。它也不允许我将其设置为 null。

我知道我需要更改 SystemColors.HighlightBrushKey,但我不知道如何设置绑定来查找父 ListViewItem 的背景颜色。这是尝试:

<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ListViewItem}}, Path=Background}" />

这可能吗?

【问题讨论】:

    标签: wpf listview background-color


    【解决方案1】:

    您是否尝试将事件处理程序附加到 SelectionChanged 事件并将 SelectedItem 设置为 null

        private void ListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var listview = sender as ListView;
    
            if (listview != null)
                listview.SelectedItem = null;
        }
    

    【讨论】:

    • 我认为您也可以尝试使用 ItemsControl 而不是 ListView,因为您无法在 ItemsControl 中选择项目。
    • 像往常一样,这就是我工作这么晚的收获。你的想法很完美。我不敢尝试将视图更改为 ItemsControl,因为它现在的定制程度非常高,所以幸运的是它解决了它。谢谢!
    【解决方案2】:

    试试这个

        <Style TargetType="ListViewItem">
            <Style.Resources>
                <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Green"/>
                    <SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="LightBlue"/>
            </Style.Resources>
        </Style>
    

    http://imduff.wordpress.com/2008/03/01/change-highlight-color-when-an-item-in-a-listview-is-selected/

    【讨论】:

    • 这是我尝试的前提,但由于背景颜色交替,我不能只设置任意颜色。我需要它来尊重行预选的颜色,因为它会根据行索引而变化。
    猜你喜欢
    • 2014-06-17
    • 1970-01-01
    • 2013-11-06
    • 2019-06-30
    • 1970-01-01
    • 1970-01-01
    • 2018-03-30
    • 2017-11-18
    • 1970-01-01
    相关资源
    最近更新 更多