views:

528

answers:

1

After selecting ListBox item programmatically it is needed to press down\up key two times to move the selection. Any suggestions?

View:

<ListBox Name="lbActions" Canvas.Left="10" Canvas.Top="10"
               Width="260" Height="180">
        <ListBoxItem Name="Open" IsSelected="true" Content="Open"></ListBoxItem>
        <ListBoxItem Name="Enter" Content="Enter"></ListBoxItem>
        <ListBoxItem Name="Print" Content="Print"></ListBoxItem>
</ListBox>

Code:

public View()
{
   lbActions.Focus();
   lbActions.SelectedIndex = 0; //not helps
   ((ListBoxItem) lbActions.SelectedItem).Focus(); //not helps either
}
+3  A: 

Don't set the focus to the ListBox... set the focus to the selected ListBoxItem. This will solve the "two keyboard strokes required" problem:

if (lbActions.SelectedItem != null)
    ((ListBoxItem)lbActions.SelectedItem).Focus();
else
    lbActions.Focus();

If your ListBox contains not something else than ListBoxItems, you can use lbActions.ItemContainerGenerator.ContainerFromIndex(lbActions.SelectedIndex) to get the automatically generated ListBoxItem.


If you want this to happen during window initialization, you need to put the code in the Loaded event rather than into the constructor. Example (XAML):

<Window ... Loaded="Window_Loaded">
    ...
</Window>

Code (based on the example in your question):

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        lbActions.Focus();
        lbActions.SelectedIndex = 0;
        ((ListBoxItem)lbActions.SelectedItem).Focus();
    }
Heinzi
I have already selected item in XAML "IsSelected="true". I provide additional selection in code, so it may be more obvious what I want to do "lbActions.SelectedIndex = 0;".
StreamT
My answer still works, just put the code *after* the `SelectedIndex = 0`.
Heinzi
Don't work for me. Item selected, this is no a problem. Keyboard navigation not works correctly after.
StreamT
Ah, only now I realized that you want *initial* focus (not focus in response to some button click). OK, I'll look into that.
Heinzi
@StreamT: Updated my answer.
Heinzi
Moving item selection code to the Windows Loaded event solves the problem
StreamT