views:

309

answers:

1

When using a Silverlight ListBox, I can programmably select an item by assigning to SelectedItem or SelectedIndex, and I can ensure that the selected item is visible to the user using the ScrollIntoView method.

Doing this the item is correctly selected (the background of that item is blue), but the keyboard focus is left on the first item in the list (the first item has the dotted border). The result is that when the user presses up or down to change the selection, the selection jumps to the top.

How can I change the "focused" item in a ListBox control to match the item I just programmably selected?

+1  A: 

Try calling my custom focus setting function (FocusEx) on your listbox after the desired events from the listbox's container (on Loaded, etc).

internal static class ControlExt
{
    // Extension for Control
    internal static bool FocusEx(this Control control)
    {
     if (control == null)
      return false;

     bool success = false;
     if (control == FocusManager.GetFocusedElement())
      success = true;
     else
     {
      // To get Focus() to work properly, call UpdateLayout() immediately before
      control.UpdateLayout();
      success = control.Focus();
     }

     ListBox listBox = control as ListBox;
     if (listBox != null)
     {
      if (listBox.SelectedIndex < 0 && listBox.Items.Count > 0)
       listBox.SelectedIndex = 0;
     }

     return success;
    }
}

That should work for you.

Jim McCurdy
This works, though it is important that both the selection and ScrollTo calls be made after using FocusEx - doing scrolling before causes the keyboard focus to become even less predictable (keyboard focus appears to get drawn to the top most visible item)
David