blins
blins

Reputation: 2535

How to implement IsSelected ListBoxItem style trigger

Why does this not work?

<ListBox>
    <ListBox.Items>
        <ListBoxItem>Foo</ListBoxItem>
        <ListBoxItem>Bar</ListBoxItem>
        <ListBoxItem>Text</ListBoxItem>
    </ListBox.Items>
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Style.Triggers>
                <Trigger Property="IsSelected" Value="True" >
                    <Setter Property="Background" Value="Red" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </ListBox.ItemContainerStyle>
</ListBox>

I.e., Background of ListBoxItem does not change when it is selected.

I was hoping to achieve this simple behavior without having to override the default item template. Surely there is a simple solution here that I am just not seeing.

Update

The only way I have found which works in both Windows 7 AND Windows 8 is by overriding the default ItemContainerStyle. This is made slightly less painful in that I can now right-click on the control in Visual Studio and Edit Style - Edit a copy... but this feels like overkill in that I am only ultimately changing the one line of XAML I commented out below. I am only showing a small relevant portion of the complete template I am forced to introduce/override.

Is there not a simpler way?

...
<MultiTrigger>
    <MultiTrigger.Conditions>
        <Condition Property="Selector.IsSelectionActive" Value="True"/>
        <Condition Property="IsSelected" Value="True"/>
    </MultiTrigger.Conditions>

    <!--<Setter Property="Background" TargetName="Bd" Value="#3D26A0DA"/>-->
    <!-- Changed above line to the following line... -->
    <Setter Property="Background" TargetName="Bd" Value="Red"/>
    <Setter Property="BorderBrush" TargetName="Bd" Value="#FF26A0DA"/>
</MultiTrigger>
...

Upvotes: 1

Views: 1209

Answers (1)

Anatoliy Nikolaev
Anatoliy Nikolaev

Reputation: 22702

Try add this in ListBox.Resources and remove IsSelected trigger:

<ListBox.Resources>
    <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Red" />
</ListBox.Resources>

In system has default highlight brush depending on your system theme. To change this value, it is necessary to turn to SystemColors.

Quote from MSDN:

The SystemColors class provides access to system brushes and colors, such as ControlBrush, ControlBrushKey, and DesktopBrush. A system brush is a SolidColorBrush object that paints an area with the specified system color. A system brush always produces a solid fill; it can't be used to create a gradient.

You can use system brushes as either a static or a dynamic resource. Use a dynamic resource if you want the brush to update automatically if the user changes the system brush as the application is running; otherwise, use a static resource.

In .NET 4.5 system does not use SystemColors, therefore, you should:

Upvotes: 1

Related Questions