Problem: I'm having trouble managing focus and item selection in a WPF ListBox with an embedded ListBox and some custom selection management in the code be开发者_如何转开发hind.
Background:
The "parent" ListBox
is assigned a DataTemplate
containing a "child" ListBox
. I have added code to navigate using the up and down arrow keys from the parent ListBoxItem
to the child items and from the child items back to the parent items.
When navigating back to a parent item which is not the first item in the first level list box the focus is always set to the first item and it is selected even though it is set in the program to a non-first item (e.g. parent item #2). I have traced through the code and the focus and selection is set to a non-first item but then another event to select and set the focus to the first item is always received.
There was another case on stackoverflow which was similar to what I am experiencing. The case is wpf listview lost the focus I tried all of the answers and responses in this case and none of them worked.
Does anyone have insight into why I can't programmatically select a non-first element in the parent ListBox
?
Try using ListBox.IsSynchronizedWithCurrentItem = true
then working with the list's collection view (if you're not explicitly creating one, you can use CollectionViewSource.GetDefaultView
) to set the current item (ICollectionView.MoveCurrentTo()
).
Selectors have a much more preferable method of dealing with selected items when working with the collection view, rather than SelectedItem
.
I have been struggling with the Focus in ListBoxes too. Perhaps the answers to these two questions will help you further. Especially the trick with setting the focus on a Background thread is very very useful.
Deselect item in ListBox
Delay change of focus
精彩评论