I have a WPF ListView control, ItemsSource is set to an ICollectionView created this way:
var collectionView =
System.Windows.Data.CollectionViewSource.Ge
Cheeso, in your previous answer you said:
But there's also a second problem with that - it doesn't work right after setting the SelectedItem. ItemContainerGenerator.ContainerFromItem() always seems to return null.
An easy solution to that is to not set SelectedItem at all. This will automatically happen when you focus the element. So just calling the following line will do:
((UIElement)this.listView1.ItemContainerGenerator.ContainerFromItem(thing)).Focus();
I was having this problem with a ListBox control (which is how I ended up finding this SO question). In my case, the SelectedItem was being set via binding, and subsequent keyboard navigation attempts would reset the ListBox to have the first item selected. I was also synchronizing my underlying ObservableCollection by adding/removing items (not by binding to a new collection each time).
Based on the info given in the accepted answer, I was able to work around it with the following subclass of ListBox:
internal class KeyboardNavigableListBox : ListBox
{
protected override void OnSelectionChanged(SelectionChangedEventArgs e)
{
base.OnSelectionChanged(e);
var container = (UIElement) ItemContainerGenerator.ContainerFromItem(SelectedItem);
if(container != null)
{
container.Focus();
}
}
}
Hope this helps someone save some time.
It's possible to focus an item with BeginInvoke
after finding it by specifying priority:
Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Loaded, new Action(() =>
{
var lbi = AssociatedObject.ItemContainerGenerator.ContainerFromIndex(existing) as ListBoxItem;
lbi.Focus();
}));