代码之家  ›  专栏  ›  技术社区  ›  Roland Illig

在中设置初始键盘焦点控件.ListView

  •  0
  • Roland Illig  · 技术社区  · 7 年前

    我有一个只有一个列表视图的窗口:

    Initial screen

    向下 ,我希望焦点移到第二行,但它停留在这个元素上。不过,虚线边框会从整个列表移动到第一个列表项:

    After pressing Tab

    此时,按下 按预期向下移动焦点。

    我从一开始就已经做了一些关于如何正确使用键盘的研究,但是没有成功。在一个 ListView AnchorItem FocusedInfo

    <Window x:Class="CSharp_Playground.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            xmlns:local="clr-namespace:CSharp_Playground"
            mc:Ignorable="d"
            Title="MainWindow" Height="350" Width="525">
    
        <Window.DataContext>
            <local:Model />
        </Window.DataContext>
    
        <ListView Name="Persons" ItemsSource="{Binding Persons}" SelectionMode="Single" />
    </Window>
    

    以及相应的C代码:

    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    
    namespace CSharp_Playground
    {
        public partial class MainWindow
        {
            public MainWindow()
            {
                InitializeComponent();
    
                Persons.SelectedIndex = 0;
                Persons.Focus();
            }
        }
    
        public class Model
        {
            public IEnumerable<string> Persons { get; } = new ObservableCollection<string>(new []{"1","2","3"});
        }
    }
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   alxnull    7 年前

    技巧似乎是显式地将焦点设置为ListView中第一个项的项容器。我找到了一个很好的解释 here .

    该博客文章的简短摘要:

    因为在创建ListView之后这些项不直接可用,所以必须在后台生成所有项之后才进行聚焦。所以,连接到 StatusChanged ItemContainerGenerator :

    Persons.ItemContainerGenerator.StatusChanged += ItemContainerGenerator_StatusChanged;
    

    在事件处理程序中,在生成所有内容后设置焦点:

    private void ItemContainerGenerator_StatusChanged(object sender, EventArgs e)
    {
       if (Persons.ItemContainerGenerator.Status == System.Windows.Controls.Primitives.GeneratorStatus.ContainersGenerated)
       {
           int index = Persons.SelectedIndex;
           if (index >= 0)
               ((ListViewItem)Persons.ItemContainerGenerator.ContainerFromIndex(index)).Focus();
       }
    }
    

    这个解决方案并不像我希望的那么简单,但它对我很有效。