[英]How to set focus on listbox item?
I have a defined list box like this:我有一个像这样定义的列表框:
var listBox = new ListBox();
listBox.Items.Add(1);
listBox.Items.Add(2);
listBox.Items.Add(3);
And I want to set focus directly to an item in the listbox.我想直接将焦点设置到列表框中的一个项目。
If I do this:如果我这样做:
listBox.SelectedIndex = 0;
listBox.Focus();
The focus is set to the entire listBox, so if I press arrow down to move the selection to the item below, I have to press the arrow twice.焦点设置在整个列表框上,所以如果我按下箭头将选择移动到下面的项目,我必须按下箭头两次。 First time the focus jumps from the entire listBox to the first item, and then when I can press the arrow again and the selection finally jumps down.
第一次焦点从整个 listBox 跳转到第一个项目,然后当我可以再次按下箭头时,选择终于向下跳了。
I want to set the focus directly to that first item, so I don't have to press the arrow twice.我想将焦点直接设置到第一项,所以我不必按两次箭头。
var listBoxItem =
(ListBoxItem)listBox
.ItemContainerGenerator
.ContainerFromItem(listBox.SelectedItem);
listBoxItem.Focus();
Here's a similar (if not equal) question Setting focus on a ListBox item breaks keyboard navigation这是一个类似(如果不相等)的问题Setting focus on a ListBox item 会破坏键盘导航
And the code (I don't mess with WPF so I can't guarantee this works, but it was accepted on the thread I linked so it might):和代码(我不会弄乱 WPF,所以我不能保证它有效,但它在我链接的线程上被接受,所以它可能):
private void Window_Loaded(object sender, RoutedEventArgs e)
{
listBox.Focus();
listBox.SelectedIndex = 0;
((ListBoxItem)listBox.SelectedItem).Focus();
}
You can't use Focus.() on a listbox item.您不能在列表框项上使用 Focus.()。 However you can select items which is pretty much the same thing as you are looking to do.
但是,您可以选择与您想要做的事情几乎相同的项目。
listbox.SelectedIndex = 0;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.