user610650
user610650

Reputation:

WPF: How can a ListBoxItem become selected when one of its controls gets focus?

Looking at the following picture you see that the TextBox in the fourth ListBoxItem has the Focus and KeyboardFocus while the second ListBoxItem is selected.

I know I can catch the GotFocus event of the Textbox, grab its DataContext, and set the IsSelected property of the bound object so the ListBoxItem becomes selected.

I'm wondering if it's possible to get the ListBoxItem selected when a user clicks any of the controls it contains? I'm asking this because I have a somewhat elaborate TreeView with a bunch of controls, and I'm looking for a simple or elegant way of having a TreeViewItem selected whenever the user clicks anywhere on it.

enter image description here

UPDATE:

I accepted Rachel's answer as it works perfectly with a ListBox, and it guided me to a solution that seems to be holding up for my TreeView: listen for the GotFocus event on TreeViewItems, and when the event occurs, set e.Handled to true to prevent the event from bubbling up to ancestors of the now selected TreeViewItem

Xaml:

<TreeView>
    <TreeView.Resources>
        <Style TargetType="TreeViewItem">
            <EventSetter Event="GotFocus" Handler="TVI_GotFocus"/>
            ...

C#:

    void TVI_GotFocus(object sender, RoutedEventArgs e)
    {
        e.Handled = true;
        if (!(sender is TreeViewItem))
            return;
        if (((TreeViewItem)sender).IsSelected)
            return;
        ((TreeViewItem)sender).IsSelected = true;
    }

Upvotes: 2

Views: 2810

Answers (2)

sellmeadog
sellmeadog

Reputation: 7517

You should also be able to setup a trigger against ListBoxItem.IsKeyboardFocusWithin and avoid any code behind:

<Style TargetType="ListBoxItem">
  <Style.Triggers>
    <Trigger Property="IsKeyboardFocusWithin" Value="True">
      <Setter Property="IsSelected" Value="True" />
    </Trigger>
  </Style.Triggers>
</Style>

Upvotes: 3

Rachel
Rachel

Reputation: 132618

Put this in your ListBox.Resources

<Style TargetType="{x:Type ListBoxItem}">
    <EventSetter Event="PreviewGotKeyboardFocus" Handler="SelectCurrentItem"/>
</Style>

And this in the Code Behind

protected void SelectCurrentItem(object sender, KeyboardFocusChangedEventArgs e)
{
    ListBoxItem item = (ListBoxItem)sender;
    item.IsSelected = true;
}

Upvotes: 1

Related Questions