Arrow keys don't work after programmatically setting ListView.SelectedItem

前端 未结 9 1731
感情败类
感情败类 2020-12-16 02:34

I have a WPF ListView control, ItemsSource is set to an ICollectionView created this way:

var collectionView = 
  System.Windows.Data.CollectionViewSource.Ge         


        
相关标签:
9条回答
  • 2020-12-16 03:10

    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();
    
    0 讨论(0)
  • 2020-12-16 03:11

    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.

    0 讨论(0)
  • 2020-12-16 03:14

    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();
    }));
    
    0 讨论(0)
提交回复
热议问题