开发者

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

开发者 https://www.devze.com 2023-03-26 03:13 出处:网络
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.

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 elegan开发者_运维技巧t way of having a TreeViewItem selected whenever the user clicks anywhere on it.

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

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;
    }


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>


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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消