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 IsKeyboardFocusWithin
property on the ItemContainerStyle
:
<ListView ItemsSource="{Binding}">
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Style.Triggers>
<Trigger Property="IsKeyboardFocusWithin" Value="True">
<Setter Property="IsSelected" Value="True" />
</Trigger>
</Style.Triggers>
</Style>
</ListView.ItemContainerStyle>
<ListView.ItemTemplate>
<DataTemplate>
<TextBox Text="{Binding Path=YourPropertyValue}" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
In this example we are simply stating that IsSelected
should 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 TextBox
Edit in response to comments
As Joep pointed out, this will mean that losing keyboard focus (which will happen when a control besides the TextBox
gains focus) will cause the IsSelected
property to be reset to false. You can work around this by replacing the Style
setter 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 SelectionMode
for the ListView
to Single
; otherwise, multiple items can become selected at once.
<ListView ItemsSource="{Binding}" SelectionMode="Single">
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Style.Triggers>
<Trigger Property="IsKeyboardFocusWithin" Value="True">
<Trigger.EnterActions>
<BeginStoryboard>
<Storyboard>
<BooleanAnimationUsingKeyFrames
Storyboard.TargetProperty="IsSelected">
<DiscreteBooleanKeyFrame KeyTime="0:0:0"
Value="True" />
</BooleanAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</Trigger.EnterActions>
</Trigger>
</Style.Triggers>
</Style>
</ListView.ItemContainerStyle>
<!-- ... -->
</ListView>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With