Wpf listbox with DataTemplate not selecting item when template control selected
I have a list box with a data template. The data template is very simple, containing two text boxes. If I click outside the text boxes on the grid around them, the list box selects the row. If I click in a text box, the text box takes the focus, but the list box does not select that row. I drew the template using Expression Blend if that 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>
See Selecting a Textbox Item in a Listbox does not change the selected item of the listbox
I thought I'd add an answer of my own to expand on what I've learned. I've done something which wasn't 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 the events fire, I eventually settled on GotFocus. The A* names were from where I was trying to rename things to see why events were not firing. Quitting Visual Studio and restarting seemed to fix it. This machine is not very reliable.
As you can see the DataTemplate is for items of type CollectionItem. I was experimenting with INotifyPropertyChanged and Observable collections. The details aren't important.
My ListBox is bound to {Binding Path=Items} where Items is an ObservableCollection
My got focus event is a variation on the solutions found in the other thread. Because my ListBox is bound directly to a list of CollectionItem objects, the following works and seems cleaner than working up the templated parent, 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 case above, sender is one of the two TextBoxes, its DataContext points at a CollectionItem, and we can set the listbox item to be selected by selecting that item.
No idea if that helps anyone, but it's out there :)
精彩评论