Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF: Setting IsSelected for ListBox when TextBox has focus, without losing selection on LostFocus

I've a ListBox with ListBoxItems with a template so they contain TextBoxes

ListBox with Textboxes

When the TextBox gets focused I want the ListBoxItem to be selected. One solution I've found looks like this:

<Style TargetType="{x:Type ListBoxItem}">
    <Style.Triggers>
        <Trigger Property="IsKeyboardFocusWithin" Value="True">
            <Setter Property="IsSelected" Value="True"></Setter>
        </Trigger>
    </Style.Triggers>
</Style>

This works great, but when the TextBox loses focus so does the selection.

Is there a way to prevent this from happening?

like image 811
Staeff Avatar asked Mar 12 '13 16:03

Staeff


1 Answers

Best solution I've found to do this with no code behinde is this:

<Style TargetType="{x:Type ListBoxItem}">
    <Style.Triggers>
        <EventTrigger RoutedEvent="PreviewGotKeyboardFocus">
            <BeginStoryboard>
                <Storyboard>
                    <BooleanAnimationUsingKeyFrames
                        Storyboard.TargetProperty="(ListBoxItem.IsSelected)">

                        <DiscreteBooleanKeyFrame KeyTime="0" Value="True"/>
                    </BooleanAnimationUsingKeyFrames>
                </Storyboard>
            </BeginStoryboard>
        </EventTrigger>
    </Style.Triggers>
</Style>
like image 144
Staeff Avatar answered Nov 11 '22 23:11

Staeff