简体   繁体   English

以编程方式选择下一个列表框项

[英]programmatically select next listbox item

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? 如何设置所选项目使其突出显示?

Your ListBox has probably just lost focus. 您的ListBox可能刚刚失去焦点。 Just do the following after setting the SelectedIndex : 设置SelectedIndex之后,只需执行以下操作:

listBox_Copy.Focus();

As GenericTypeTea says, it sounds likely that it's to do with lost focus. 正如GenericTypeTea所说,听起来可能与失去焦点有关。 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;
}            

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM