bradgonesurfing
bradgonesurfing

Reputation: 32202

How to latch the SelectedIndex on a WPF listbox when a child control has focus

I currently have

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

However the problem is that the SelectedIndex returns to -1 when I give some other control on the UI focus. The behaviour I am looking for is that the ListBoxItem is selected when a child gains focus but does not reset when the child loses focus.

Upvotes: 0

Views: 222

Answers (1)

LPL
LPL

Reputation: 17083

Replace the Trigger with an EventTrigger then IsSelected isn't returning to original state:

<EventTrigger RoutedEvent="PreviewGotKeyboardFocus">
    <BeginStoryboard>
        <Storyboard>
            <BooleanAnimationUsingKeyFrames Storyboard.TargetProperty="IsSelected">
                <DiscreteBooleanKeyFrame Value="True" KeyTime="0:0:0" />
            </BooleanAnimationUsingKeyFrames>
        </Storyboard>
    </BeginStoryboard>                          
</EventTrigger>

From MSDN

Unlike Trigger, EventTrigger has no concept of termination of state, so the action will not be undone once the condition that raised the event is no longer true.

PS: I have tried this for SelectionMode="Single" only.

Upvotes: 1

Related Questions