How can I set the focus to a ListBox properly on load if it uses databinding?

做~自己de王妃 提交于 2019-12-01 03:04:07

问题


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.

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

  }

EDIT: 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();
}

回答1:


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

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.




回答2:


The FocusManager.SetFocusedElement method gives logical focus, but not keyboard focus. You can use the Keyboard.Focus method to give keyboard focus to an element. Have a look at this page for more details about focus management in WPF.



来源:https://stackoverflow.com/questions/2283143/how-can-i-set-the-focus-to-a-listbox-properly-on-load-if-it-uses-databinding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!