ListView SelectedItem交替背景颜色

时间:2011-07-27 05:20:42

标签: wpf listview background-color

我在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}" />

这可能吗?

2 个答案:

答案 0 :(得分:2)

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

    private void ListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        var listview = sender as ListView;

        if (listview != null)
            listview.SelectedItem = null;
    }

答案 1 :(得分:-1)

试试这个

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