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