I thought I would add my answer to expand on what I learned. I did what was not shown in the linked answer above.
So I have a DataTemplate:
<DataTemplate DataType="{x:Type Scratch:CollectionItem}"> <Grid Height="20" Width="288"> <TextBox HorizontalAlignment="Left" Margin="8,0,0,0" TextWrapping="Wrap" Text="{Binding Id}" VerticalAlignment="Top" Width="86" PreviewMouseDown="APreviewMouseDown" GotFocus="AGotFocus" GotKeyboardFocus="AGotKeyboardFocus" PreviewGotKeyboardFocus="AGotKeyboardFocus"/> <TextBox Margin="98,0,0,0" TextWrapping="Wrap" Text="{Binding Detail}" VerticalAlignment="Top" PreviewMouseDown="APreviewMouseDown" GotFocus="AGotFocus" GotKeyboardFocus="AGotKeyboardFocus" PreviewGotKeyboardFocus="AGotKeyboardFocus"/> </Grid>
All events shoot, I eventually settled in GotFocus. A * names were from the place where I tried to rename things in order to understand why events do not shoot. Exiting Visual Studio and restarting seems to fix it. This car is not very reliable.
As you can see, the DataTemplate is for elements of type CollectionItem. I experimented with the INotifyPropertyChanged and Observable collections. Details are not important.
My ListBox is bound to {Binding Path = Items}, where Items is an ObservableCollection
My focus event is a variation of the solutions found in another thread. Since my ListBox is directly linked to the list of CollectionItem objects, the following works and seems cleaner than handling the parent template, etc.
private void AGotFocus(object sender, RoutedEventArgs e) { try { FrameworkElement element = sender as FrameworkElement; CollectionItem item = element.DataContext as CollectionItem; if (item != null) { listBox2.SelectedValue = item; } } catch { } }
So, in the above case, the sender is one of two text fields, its DataContext points to CollectionItem, and we can set the list item to be selected by selecting this item.
I don’t know if this helps anyone, but it is there :)