以编程方式选择下一个列表框项目
我正在尝试对两个按钮进行编程以模仿向上/向下箭头键的行为,这意味着当我按下向上按钮时,它会在列表框中向上移动一项,依此类推。我编写了以下代码:
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;
}
}
这是有效的,但是,当按下按钮时,该项目将失去其选择...选择索引设置正确(绑定到所选项目的其他数据绑定项目显示正确的值),但列表框项目不是不再突出显示。如何设置所选项目突出显示?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的列表框可能刚刚失去焦点。设置
SelectedIndex
后只需执行以下操作:Your ListBox has probably just lost focus. Just do the following after setting the
SelectedIndex
:正如 GenericTypeTea 所说,这听起来很可能与失去焦点有关。然而,另一个问题是您的代码过于复杂,不允许您转到顶部的项目。我建议将其更改为:
向上移动
向下移动
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
Move down