【问题标题】:Arrow keys don't work after programmatically setting ListView.SelectedItem以编程方式设置 ListView.SelectedItem 后箭头键不起作用
【发布时间】:2011-11-13 21:27:51
【问题描述】:

我有一个 WPF ListView 控件,ItemsSource 设置为这样创建的 ICollectionView:

var collectionView = 
  System.Windows.Data.CollectionViewSource.GetDefaultView(observableCollection);
this.listView1.ItemsSource = collectionView;

...其中 observableCollection 是复杂类型的 ObservableCollection。 ListView 被配置为对每个项目仅显示复杂类型的一个字符串属性。

用户可以刷新 ListView,此时我的逻辑存储当前选定项的“键字符串”,重新填充底层 observableCollection。然后将前面的排序和过滤器应用到 collectionView。此时我想“重新选择”在请求刷新之前已选择的项目。 observableCollection 中的项目是新实例,所以我比较了各自的字符串属性,然后只选择一个匹配的。像这样:

private void SelectThisItem(string value)
{
    foreach (var item in collectionView) // for the ListView in question
    {
        var thing = item as MyComplexType;
        if (thing.StringProperty == value)
        {
            this.listView1.SelectedItem = thing;
            return;
        }
    }
}

这一切都有效。如果选择了第 4 项,并且用户按 F5,则重新构建列表,然后选择与前第 4 项具有相同字符串属性的项。有时这是新的第 4 项,有时不是,但它提供“least astonishment behavior”。

当用户随后使用箭头键在 ListView 中导航时,问题就出现了。刷新后的第一个向上或向下箭头会导致选择(新)列表视图中的第一个项目,无论之前的逻辑选择了哪个项目。任何进一步的箭头键都按预期工作。

为什么会这样?

这显然违反了“最小惊讶”规则。如何避免?


编辑
经过进一步搜索,这似乎与 unanswered
WPF ListView arrow navigation and keystroke problem 所描述的异常情况相同,但我提供了更多详细信息。

【问题讨论】:

    标签: wpf listview observablecollection icollectionview


    【解决方案1】:

    Cheeso 的解决方案对我有用。通过设置timer.tick 来防止null 异常,因此您已经离开了原来的例程。

    var uiel = (UIElement)this.lv1.ItemContainerGenerator                        
               .ContainerFromItem(lv1.Items[ix]); 
    if (uiel != null) uiel.Focus();
    

    在RemoveAt/Insert 之后调用计时器时问题已解决,并且在Window.Loaded 处设置焦点并选择第一项。

    想回馈我在 SE 获得的许多灵感和解决方案的第一篇文章。编码愉快!

    【讨论】:

      【解决方案2】:

      通过指定优先级找到BeginInvoke 后,可以将其聚焦:

      Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Loaded, new Action(() =>
      {
          var lbi = AssociatedObject.ItemContainerGenerator.ContainerFromIndex(existing) as ListBoxItem;
          lbi.Focus();
      }));
      

      【讨论】:

        【解决方案3】:

        我发现了一种不同的方法。我使用数据绑定来确保在代码中突出显示正确的项目,然后我没有将焦点设置在每次重新绑定上,而是简单地在代码后面添加一个事件前处理程序以进行键盘导航。像这样。

            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;
            }
        

        这只是确保在让 WPF 处理按键之前设置正确的焦点

        【讨论】:

          【解决方案4】:

          我在使用 ListBox 控件时遇到了这个问题(这就是我最终找到这个 SO 问题的方式)。在我的例子中,SelectedItem 是通过绑定设置的,随后的键盘导航尝试将重置 ListBox 以选择第一个项目。我还通过添加/删除项目(而不是每次都绑定到新集合)来同步我的底层 ObservableCollection。

          根据接受的答案中给出的信息,我能够使用以下 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();
                  }
              }
          }
          

          希望这可以帮助某人节省一些时间。

          【讨论】:

            【解决方案5】:

            经过一番折腾,我无法让它在 MVVM 中工作。 我自己试了一下,使用了 DependencyProperty。这对我很有用。

            public class ListBoxExtenders : DependencyObject
            {
                public static readonly DependencyProperty AutoScrollToCurrentItemProperty = DependencyProperty.RegisterAttached("AutoScrollToCurrentItem", typeof(bool), typeof(ListBoxExtenders), new UIPropertyMetadata(default(bool), OnAutoScrollToCurrentItemChanged));
            
                public static bool GetAutoScrollToCurrentItem(DependencyObject obj)
                {
                    return (bool)obj.GetValue(AutoScrollToSelectedItemProperty);
                }
            
                public static void SetAutoScrollToCurrentItem(DependencyObject obj, bool value)
                {
                    obj.SetValue(AutoScrollToSelectedItemProperty, value);
                }
            
                public static void OnAutoScrollToCurrentItemChanged(DependencyObject s, DependencyPropertyChangedEventArgs e)
                {
                    var listBox = s as ListBox;
                    if (listBox != null)
                    {
                        var listBoxItems = listBox.Items;
                        if (listBoxItems != null)
                        {
                            var newValue = (bool)e.NewValue;
            
                            var autoScrollToCurrentItemWorker = new EventHandler((s1, e2) => OnAutoScrollToCurrentItem(listBox, listBox.Items.CurrentPosition));
            
                            if (newValue)
                                listBoxItems.CurrentChanged += autoScrollToCurrentItemWorker;
                            else
                                listBoxItems.CurrentChanged -= autoScrollToCurrentItemWorker;
                        }
                    }
                }
            
                public static void OnAutoScrollToCurrentItem(ListBox listBox, int index)
                {
                    if (listBox != null && listBox.Items != null && listBox.Items.Count > index && index >= 0)
                        listBox.ScrollIntoView(listBox.Items[index]);
                }
            
            }
            

            在 XAML 中的使用

            <ListBox IsSynchronizedWithCurrentItem="True" extenders:ListBoxExtenders.AutoScrollToCurrentItem="True" ..../>
            

            【讨论】:

              【解决方案6】:

              这一切似乎有点干扰......我自己重写了逻辑:

              public class CustomListView : ListView
              {
                          protected override void OnPreviewKeyDown(KeyEventArgs e)
                          {
                              // Override the default, sloppy behavior of key up and down events that are broken in WPF's ListView control.
                              if (e.Key == Key.Up)
                              {
                                  e.Handled = true;
                                  if (SelectedItems.Count > 0)
                                  {
                                      int indexToSelect = Items.IndexOf(SelectedItems[0]) - 1;
                                      if (indexToSelect >= 0)
                                      {
                                          SelectedItem = Items[indexToSelect];
                                          ScrollIntoView(SelectedItem);
                                      }
                                  }
                              }
                              else if (e.Key == Key.Down)
                              {
                                  e.Handled = true;
                                  if (SelectedItems.Count > 0)
                                  {
                                      int indexToSelect = Items.IndexOf(SelectedItems[SelectedItems.Count - 1]) + 1;
                                      if (indexToSelect < Items.Count)
                                      {
                                          SelectedItem = Items[indexToSelect];
                                          ScrollIntoView(SelectedItem);
                                      }
                                  }
                              }
                              else
                              {
                                  base.OnPreviewKeyDown(e);
                              }
                          }
              }
              

              【讨论】:

                【解决方案7】:

                Cheeso,在你的previous answer 你说:

                但还有第二个问题 - 它不能正常工作 设置 SelectedItem 后。 ItemContainerGenerator.ContainerFromItem() 似乎总是返回 空。

                一个简单的解决方案是根本不设置 SelectedItem。当您聚焦元素时,这将自动发生。所以只需调用以下行即可:

                ((UIElement)this.listView1.ItemContainerGenerator.ContainerFromItem(thing)).Focus();
                

                【讨论】:

                • 我想我试过了,但没用。无论如何,现在已经过了很长时间,我已经过去了。不过可能对面临类似问题的人有用。
                【解决方案8】:

                看起来这是由于a sort of known but not-well-described problematic behavior with ListView(可能还有其他一些 WPF 控件)。在以编程方式设置 SelectedItem 之后,它要求应用程序在特定 ListViewItem 上调用 Focus()。

                但 SelectedItem 本身不是 UIElement。它是您在 ListView 中显示的任何项目,通常是自定义类型。因此您不能致电this.listView1.SelectedItem.Focus()。那是行不通的。您需要获取显示该特定项目的 UIElement(或 Control)。 WPF 界面有一个名为ItemContainerGenerator 的暗角,据说它可以让您获得在ListView 中显示特定项目的控件。

                类似这样的:

                this.listView1.SelectedItem = thing;
                // *** WILL NOT WORK!
                ((UIElement)this.listView1.ItemContainerGenerator.ContainerFromItem(thing)).Focus();
                

                但还有第二个问题 - 在设置 SelectedItem 后它无法正常工作。 ItemContainerGenerator.ContainerFromItem() 似乎总是返回 null。在 googlespace 的其他地方,人们报告它返回 null 并设置了 GroupStyle。但它在我身上表现出这种行为,没有分组。

                ItemContainerGenerator.ContainerFromItem() 正在为列表中显示的所有对象返回 null。 ItemContainerGenerator.ContainerFromIndex() 也为所有指标返回 null。只有在 ListView 被渲染(或其他东西)之后才调用这些东西。

                我尝试通过Dispatcher.BeginInvoke() 直接执行此操作,但这也不起作用。

                在其他一些线程的建议下,我在ItemContainerGenerator 的StatusChanged 事件中使用了Dispatcher.BeginInvoke()。是的,很简单吧? (不)

                代码如下所示。

                MyComplexType current;
                
                private void SelectThisItem(string value)
                {
                    foreach (var item in collectionView) // for the ListView in question
                    {
                        var thing = item as MyComplexType;
                        if (thing.StringProperty == value)
                        {
                            this.listView1.ItemContainerGenerator.StatusChanged += icg_StatusChanged;
                            this.listView1.SelectedItem = thing;
                            current = thing;
                            return;
                        }
                    }
                }
                
                
                void icg_StatusChanged(object sender, EventArgs e)
                {
                    if (this.listView1.ItemContainerGenerator.Status
                        == System.Windows.Controls.Primitives.GeneratorStatus.ContainersGenerated)
                    {
                        this.listView1.ItemContainerGenerator.StatusChanged
                            -= icg_StatusChanged;
                        Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Input,
                                               new Action(()=> {
                                                       var uielt = (UIElement)this.listView1.ItemContainerGenerator.ContainerFromItem(current);
                                                       uielt.Focus();}));
                
                    }
                }
                

                那是一些丑陋的代码。但是,以这种方式以编程方式设置 SelectedItem 允许后续箭头导航在 ListView 中工作。

                【讨论】:

                • 我有类似的,要求 dispatch.begininvokes 稍后将“重新聚焦”。不要忘记将自己标记为答案!
                • 我打算接受这个作为答案,但我想我还不能——有一个计时器。
                • 丑陋,甚至不可靠。片刻之后,ListBox 获得焦点(您可以看到焦点矩形),然后项目再次获得焦点。在那一刻按下箭头键时,您的选择消失了。
                【解决方案9】:

                以编程方式选择项目不会为其提供键盘焦点。你必须明确地这样做......((Control)listView1.SelectedItem).Focus()

                【讨论】:

                • 谢谢。抛出。 ListView 中显示的 Item 不是 Control,因此演员会抛出。我也试了this.listView1.Focus(),虽然不会抛出,但是我看也没什么区别。
                猜你喜欢
                • 2013-05-06
                • 1970-01-01
                • 1970-01-01
                • 2017-01-17
                • 1970-01-01
                • 1970-01-01
                • 2019-11-11
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多