programmatically select next listbox item

internetmw picture internetmw · Jul 28, 2010 · Viewed 11.3k times · Source

I'm trying to program two buttons to imitate the up/down arrow key behavior, meaning that when I press the button for up, it moves up one item in my listbox 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 pressing the button the item loses its selection... The selection index is set properly (other databinded items, binded to selected item show the correct values) but the listbox item isn't highlighted anymore. How do I set the selected item to become highlighted?

Answer

djdd87 picture djdd87 · Jul 28, 2010

Your ListBox has probably just lost focus. Just do the following after setting the SelectedIndex:

listBox_Copy.Focus();