You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WinUI中如何获取/设置GridView的键盘导航高亮项?

WinUI GridView键盘导航焦点项的获取与处理方案

核心概念澄清

GridView中**焦点项(高亮显示)和选中项(SelectedItem/SelectedIndex)**是两个独立状态:

  • 鼠标点击时,会同时设置焦点和选中状态,所以两者一致;
  • 键盘方向键导航时,仅移动焦点(即你看到的高亮项),默认不会自动修改选中状态,这就是你遇到“第一项高亮但第二项是选中项”的原因。

获取当前焦点项的方法

方法1:通过子项的GotFocus事件(你已添加该事件)

在Panel_GotFocus事件中直接获取绑定的数据项:

private void Panel_GotFocus(object sender, RoutedEventArgs e)
{
    var stackPanel = sender as StackPanel;
    // 拿到当前焦点项绑定的数据对象
    var focusedItem = stackPanel?.DataContext as Item;
    
    // 可选:如果需要让焦点项自动同步为选中项,添加以下代码
    if (focusedItem != null)
    {
        ImageGridView.SelectedItem = focusedItem;
    }
}

方法2:主动查询当前焦点元素

通过FocusManager获取GridView范围内的焦点元素,再提取数据项:

private Item GetFocusedGridViewItem()
{
    var focusedElement = FocusManager.GetFocusedElement(ImageGridView) as FrameworkElement;
    return focusedElement?.DataContext as Item;
}

设置指定项为焦点项

如果需要主动将焦点定位到某个数据项,可通过ContainerFromItem获取对应的GridView容器,再设置焦点:

private void SetFocusToItem(Item targetItem)
{
    var itemContainer = ImageGridView.ContainerFromItem(targetItem) as GridViewItem;
    if (itemContainer != null)
    {
        // 设置焦点,FocusState根据场景选择(Programmatic/Keyboard等)
        itemContainer.Focus(FocusState.Programmatic);
        // 可选:同步选中状态
        ImageGridView.SelectedItem = targetItem;
    }
}

监听键盘导航事件

如果需要监听键盘方向键的导航行为,可给GridView添加KeyDown事件:

private void ImageGridView_KeyDown(object sender, KeyRoutedEventArgs e)
{
    if (e.Key == VirtualKey.Left || e.Key == VirtualKey.Right || 
        e.Key == VirtualKey.Up || e.Key == VirtualKey.Down)
    {
        // 键盘导航触发,可在此处获取当前焦点项做处理
        var currentFocusedItem = GetFocusedGridViewItem();
        // 执行你的业务逻辑
    }
}

补充说明

若希望键盘导航时自动同步焦点与选中状态,除了在GotFocus中手动设置,也可以修改GridView的IsSynchronizedWithCurrentItem属性为True,这样焦点项会自动同步到SelectedItem。

内容的提问来源于stack exchange,提问作者vishalb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 01:37:39