I have the following ListView (simplified):
<ListView Name="lvwNotes" KeyUp="lvwNotes_KeyUp">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical">
<DockPanel Background="LightGray">
<TextBlock DockPanel.Dock="Right" Text="{Binding Path=Author}" />
<TextBlock Text="{Binding Path=Timestamp}" />
</DockPanel>
<TextBox Text="{Binding Path=Text}"
GotFocus = "lvwNotes_TextBox_GotFocus"
TextWrapping="Wrap" />
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
Changing the selected item through a click only works when the user clicks on the DockPanel with the TextBlocks, but not on clicking the TextBox. What I want to achieve is to set the selected item to that one containing the TextBox into which the user clicked.
I managed to get through to the ListViewItem related to the TextBox:
private void lvwNotes_TextBox_GotFocus(object sender, RoutedEventArgs e) {
DependencyObject o = Tools.GetAncestorByType((DependencyObject)sender, typeof(ListViewItem));
if (!o.Equals(null)) {
// code to select this ListViewItem
}
}
But setting
lvwNotes.SelectedIten = o ;
remains without effect. I've tried also some tricks with Dispatcher.BeginInvoke, but to be honest, I don't exactly know what I'm doing there.
Add this to your code
<ListView.Resources>
<Style TargetType="ListViewItem">
<Style.Triggers>
<Trigger Property="IsKeyboardFocusWithin" Value="True">
<Setter Property="IsSelected" Value="True" />
</Trigger>
</Style.Triggers>
</Style>
</ListView.Resources>