4
votes

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?

2

2 Answers

2
votes

As GenericTypeTea says, it sounds likely that it's to do with lost focus. Another issue however is that your code is overcomplicated and won't let you go up to the item at the top. I'd 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;
}            
5
votes

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

listBox_Copy.Focus();