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

前端 未结 9 1766
感情败类
感情败类 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:06

    I found a somewhat different approach. I'm using databinding to make sure the correct item is highlighted in the code, and then instead of setting focus on every rebind, I simply add a pre-event handler to the code behind for keyboard navigation. Like this.

        public MainWindow()
        {
             ...
             this.ListView.PreviewKeyDown += this.ListView_PreviewKeyDown;
        }
    
        private void ListView_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            UIElement selectedElement = (UIElement)this.ListView.ItemContainerGenerator.ContainerFromItem(this.ListView.SelectedItem);
            if (selectedElement != null)
            {
                selectedElement.Focus();
            }
    
            e.Handled = false;
        }
    

    This simply makes sure that the correct focus is set before letting WPF handle the keypress

提交回复
热议问题