Wpf list with DataTemplate does not select an item if a template control is selected

I have a window with a data template. The data template is very simple, containing two text fields. If I am outside the text fields on the grid around them, a row is selected in the list box. If I click in the text field, the text field is given focus, but this line is not selected in the list. I drew a template using Expression Blend if this helps explain some of the values, Margin, etc.

Here is the data template:

<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"/> <TextBox Margin="98,0,0,0" TextWrapping="Wrap" Text="{Binding Detail}" VerticalAlignment="Top"/> </Grid> </DataTemplate> 
+4
source share
2 answers

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 :)

+1
source

Source: https://habr.com/ru/post/1333040/


All Articles