Possible Duplicate:
Select ListBoxItem if TextBox in ItemTemplate gets focus
I have a ListView bound to an ObservableCollection (Listview.ItemsSource). The listview presents several textboxes that are bound to properties of the objects in the observable collection.
I would like to have the following functionality: when a user focusses a textbox the corresponding item in the listview should get selected.
I have tried things with ContainerFromElement, ContainerFromItem, etc. but can’t get this “simple” functionality to work.
Any ideas…
The trick here is to use the
IsKeyboardFocusWithinproperty on theItemContainerStyle:In this example we are simply stating that
IsSelectedshould be set to true whenever a control within that item contains the keyboard focus.Note: this does not work in the opposite direction; selecting a particular item in the list will not automatically give focus to the contained
TextBoxEdit in response to comments
As Joep pointed out, this will mean that losing keyboard focus (which will happen when a control besides the
TextBoxgains focus) will cause theIsSelectedproperty to be reset to false. You can work around this by replacing theStylesetter with an trigger enter action, which prevents the change from being undone when the trigger is no longer valid.For this to work in the same way as the previous example you will need to explicitly set the
SelectionModefor theListViewtoSingle; otherwise, multiple items can become selected at once.