Scott Salyer
Scott Salyer

Reputation: 2475

ListView SelectedItem Alternating Background Color

I am using (new to 3.5) AlternationIndex trigger on a ListView to apply an alternating background color like this:

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

This part works great and the ListView looks exactly how I want. The only issue I have is with the SelectedItem's background color. For my list, items can't actually be selected since contextually that makes no sense. What I am trying to find is a way to have the SelectedItem's background color be nothing so the parent ListViewItem's color shines through. Transparent doesn't work because that essentially equates to white and the alternating style disappears when I use transparent. It also wouldn't let me set it to null.

I know I need to change the SystemColors.HighlightBrushKey, but I couldn't figure out how to setup the binding to find the parent ListViewItem's background color. Here was the attempt:

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

Is this possible to do?

Upvotes: 1

Views: 1355

Answers (2)

Kishore Kumar
Kishore Kumar

Reputation: 21863

just try with this

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

Upvotes: -1

Filip
Filip

Reputation: 652

Have you tried attaching a event handler to the SelectionChanged event and set SelectedItem to null

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

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

Upvotes: 2

Related Questions