Selecting a Textbox Item in a Listbox does not change the selected item of the listbox
We use the following style to set a PreviewGotKeyboardFocus which handles all events of TextBox control and ComboBoxes and such:
<ListView.ItemContainerStyle> <Style TargetType="ListViewItem"> <EventSetter Event="PreviewGotKeyboardFocus" Handler="SelectCurrentItem"/> </Style> </ListView.ItemContainerStyle>
And then we select the row in code behind:
protected void SelectCurrentItem(object sender, KeyboardFocusChangedEventArgs e) { ListViewItem item = (ListViewItem) sender; item.IsSelected = true; }
Be sure to use appropriate TargetType: ListViewItem, ListBoxItem or TreeViewItem.
<Style TargetType="ListViewItem"> <Style.Triggers> <Trigger Property="IsKeyboardFocusWithin" Value="true"> <Setter Property="IsSelected" Value="true" /> </Trigger> </Style.Triggers></Style>
I don't have enough reps to comment, so I am posting my comment as answer. Grazer's solution above does not work in cases where you have another control such as a Button
that needs the SelectedItem
. This is because as per the Style Trigger
, the IsKeyboardFocusWithin
becomes false when you click on that Button
, and the SelectedItem
becomes null.