How to use IsKeyboardFocusWithin and IsSelected together?

Posted by jpsstavares on Stack Overflow See other posts from Stack Overflow or by jpsstavares
Published on 2010-06-11T11:29:37Z Indexed on 2010/06/11 13:22 UTC
Read the original article Hit count: 316

Filed under:
|
|

I have a style defined for my ListBoxItems with a trigger to set a background color when IsSelected is True:

    <Style x:Key="StepItemStyle" TargetType="{x:Type ListBoxItem}">
        <Setter Property="SnapsToDevicePixels" Value="true"/>
        <Setter Property="OverridesDefaultStyle" Value="true"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="ListBoxItem">
                    <Border Name="Border" Padding="0" SnapsToDevicePixels="true">
                        <ContentPresenter />
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsSelected" Value="True">
                            <Setter TargetName="Border" Property="Background" Value="#40a0f5ff"/>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

This style maintains the selected item even when the ListBox and ListBoxItem loses focus, which in my case is an absolute must. The problem is that I also want the ListBoxItem to be selected when one of its TextBox's child gets focused. To achieve this I add a trigger that sets IsSelected to true when IsKeyboardFocusWithin is true:

<Trigger Property="IsKeyboardFocusWithin" Value="True">
    <Setter Property="IsSelected" Value="True" />
</Trigger>

When I add this trigger the Item is selected when the focus is on a child TextBox, but the first behaviour disappears. Now when I click outside the ListBox, the item is de-selected.

How can I keep both behaviours?

© Stack Overflow or respective owner

Related posts about wpf

Related posts about listbox