如果 ListBox 使用数据绑定,如何在加载时将焦点正确设置到 ListBox? [英] How can I set the focus to a ListBox properly on load if it uses databinding?

查看:38
本文介绍了如果 ListBox 使用数据绑定,如何在加载时将焦点正确设置到 ListBox?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通常在 Loaded 事件处理程序中调用 myControl.Focus(),但这似乎不适用于数据绑定到自定义列表的 ListBox对象.当我启动我的应用程序时,ListBox 的第一项被选中,但焦点在其他地方.

I usually call myControl.Focus() in the Loaded event handler, but this doesn't seem to work for a ListBox which is databound to a list of custom objects. When I start my application, the ListBox's first item is selected but the focus is elsewhere.

我认为这可能是因为在将数据绑定项加载到其中之前设置了焦点...但是以下代码显示确实有项,因为 ctrlItemsCount 显示数字 8.

I thought this could be because the focus is being set before the databound items are loaded into it... but the following code shows that there are indeed items because ctrlItemsCount shows the number 8.

在这种情况下如何设置初始焦点,通常设置初始焦点的正确位置是什么?

How can I set the initial focus in this situation, and what is the correct place to set initial focus usually?

private void onLoad(object sender, RoutedEventArgs e) {
        if (ctrlCountries.Items.Count > 0) {
             ctrlItemsCount.Text = ctrlCountries.Items.Count;
             ctrlCountries.SelectedIndex = 0;
             FocusManager.SetFocusedElement(this, ctrlCountries);
        }

  }

我已将此代码移动到实际 ListBox 本身的加载事件中.它几乎可以工作 - 现在焦点位于 ListBox 上,但我仍然需要在项目 #0 出现键盘光标之前按一次键盘 DOWN.换句话说,由于某种原因,焦点或光标比第 0 项高 1 个等级:

I have moved this code to the loaded event for the actual ListBox itself. It almost works - the focus is now on the ListBox, but I still need to press keyboard DOWN once before item #0 has the keyboard cursor. In other words, the focus, or cursor, is 1 notch above item #0 for some reason:

private void onCountriesLoaded(object sender, RoutedEventArgs e) {
    ctrlCountries.SelectedIndex = 0;
    FocusManager.SetFocusedElement(this, ctrlCountries);
    Keyboard.Focus();
}

推荐答案

如果要聚焦列表框中的第一个元素,则必须将焦点设置到第一个 ListBoxItem 容器.例如:

If you want to focus the first element in the list box you have to set the focus to the first ListBoxItem container. For example:

if (myListBox.Items.Count > 0)
{ 
   ListBoxItem item = (ListBoxItem)myListBox.ItemContainerGenerator.ContainerFromIndex(0);
   FocusManager.SetFocusedElement(this /* focus scope region */, item);
}

您仍然必须确保 ListBox 控件首先收到了它的 Loaded 事件.还有许多其他事件可用于处理与列表框项相关的更新.查看 MSDN 中的 ItemContainerGenerator.

You still have to make sure though, that the ListBox control has first received its Loaded event. There are a number of other events that are useful for handling list box item related updates. Have a look at the ItemContainerGenerator in MSDN.

这篇关于如果 ListBox 使用数据绑定,如何在加载时将焦点正确设置到 ListBox?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆