Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

After selecting ListBox item programmatically it is needed to press downup 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
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.1k views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...