Programmatically select the next list item

I am trying to program two buttons to simulate the behavior of an up / down arrow key, which means that when I press the up button, it moves up one item in my list and so on. I wrote the following code:

private void mainlistup(object sender, System.Windows.RoutedEventArgs e) { if (listBox_Copy.SelectedIndex != -1 && listBox_Copy.SelectedIndex < listBox_Copy.Items.Count && listBox_Copy.SelectedIndex !=1) { listBox_Copy.SelectedIndex = listBox_Copy.SelectedIndex - 1; } } private void mainlistdown(object sender, System.Windows.RoutedEventArgs e) { if (listBox_Copy.SelectedIndex < listBox_Copy.Items.Count && listBox_Copy.SelectedIndex != -1) { listBox_Copy.SelectedIndex = listBox_Copy.SelectedIndex + 1; } } 

This works, however, when you click the button, the item loses its choice ... The selection index is set correctly (other data items bound to the selected item display the correct values), but the list item is no longer highlighted. How to set a selected item for selection?

+4
source share
2 answers

As GenericTypeTea says, this seems to be due to lost focus. Another problem is that your code is too complex and will not allow you to jump to the element at the top. I would suggest changing it to something like:

Move up

 if (listBox_Copy.SelectedIndex > 0) { listBox_Copy.SelectedIndex = listBox_Copy.SelectedIndex - 1; } 

Move down

 if (listBox_Copy.SelectedIndex < listBox_Copy.Items.Count - 1) { listBox_Copy.SelectedIndex = listBox_Copy.SelectedIndex + 1; } 
+2
source

Your ListBox probably just lost focus. Follow these steps after installing SelectedIndex :

 listBox_Copy.Focus(); 
+5
source

All Articles