I have a ListBox which presents objects using a DataTemplate. The DataTemplate contains a TextBox. When the user selects an item in the ListBox, I would like to set focus to the TextBox for the selected item.
I have been able to partially achieve this by handling ListBox.SelectionChanged, but it only works when the user clicks on the ListBox to select the item - it does not work if the user tabs into the ListBox and uses the arrow keys to select the item even though TextBox.Focus() is invoked.
How can I set focus to the TextBox when the user uses the keyboard to select an item?
Here is the markup for the ListBox:
<ListBox Name="lb1" SelectionChanged="ListBox_SelectionChanged" ItemsSource="{Binding Items}" > <ListBox.ItemTemplate> <DataTemplate > <TextBox></TextBox> </DataTemplate> </ListBox.ItemTemplate> </ListBox> Here is the handling code:
private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { ListBoxItem lbi = (ListBoxItem)this.lb1.ItemContainerGenerator.ContainerFromItem(this.lb1.SelectedItem); Visual v = GetDescendantByType<TextBox>(lbi); TextBox tb = (TextBox)v; tb.Focus(); }