开发者

programmatically select next listbox item

开发者 https://www.devze.com 2023-01-09 10:13 出处:网络
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:

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 t开发者_如何学Che listbox item isn't highlighted anymore. How do I set the selected item to become highlighted?


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

listBox_Copy.Focus();


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;
}            
0

精彩评论

暂无评论...
验证码 换一张
取 消