SG_90
SG_90

Reputation: 305

List Box Item gets deselected when its TextBox looses focus

In my application I have a ListBox whose ListBoxItems are rendered as TextBoxes. I want the item to get selected whenever the TextBox gains keyboard focus. I have applied a following Trigger to it:

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

However, what I don't want is the item to get deselected when the TextBox looses focus, and this is what I currently get. This means that I'm unable to, for instance, change the font size within the TextBox by choosing it from a ComboBox.

The above code is defined in a Template in a ResourceDictionary file.

Upvotes: 1

Views: 431

Answers (1)

dkozl
dkozl

Reputation: 33364

You could use Storyboard to select your item when it gets focus so it works only for selecting

    <ListBox ...>
        <ListBox.ItemTemplate>
            <!-- your DataTemplate -->
        </ListBox.ItemTemplate>
        <ListBox.ItemContainerStyle>
            <Style TargetType="{x:Type ListBoxItem}">
                <Style.Triggers>
                    <EventTrigger RoutedEvent="GotKeyboardFocus">
                        <BeginStoryboard>
                            <Storyboard>
                                <BooleanAnimationUsingKeyFrames Storyboard.TargetProperty="IsSelected">
                                    <DiscreteBooleanKeyFrame Value="True" KeyTime="0:0:0"/>
                                </BooleanAnimationUsingKeyFrames>
                            </Storyboard>
                        </BeginStoryboard>
                    </EventTrigger>
                </Style.Triggers>
            </Style>
        </ListBox.ItemContainerStyle>
    </ListBox>

this way item won't be automatically unselected when it looses focus

Upvotes: 3

Related Questions