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
}
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 your ListBox contains something else than
ListBoxItems, you can uselbActions.ItemContainerGenerator.ContainerFromIndex(lbActions.SelectedIndex)to get the automatically generatedListBoxItem.If you want this to happen during window initialization, you need to put the code in the
Loadedevent rather than into the constructor. Example (XAML):Code (based on the example in your question):