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

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

问题描述

我通常在加载的事件处理程序中调用 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);
        }

  }

编辑: strong>我已将此代码移动到实际的 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();
}


推荐答案

列表框中的第一个元素必须将焦点设置为第一个 ItemBoxItem 容器。例如:

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

你还需要确定, em>控件首先收到了 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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