wpf 如何将焦点设置在列表框项目上?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24110679/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set focus on listbox item?
提问by user3595338
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.
我想将焦点直接设置到第一项,所以我不必按两次箭头。
回答by Noor E Alam Robin
var listBoxItem =
(ListBoxItem)listBox
.ItemContainerGenerator
.ContainerFromItem(listBox.SelectedItem);
listBoxItem.Focus();
回答by markhc
Here's a similar (if not equal) question Setting focus on a ListBox item breaks keyboard navigation
这是一个类似(如果不相等)的问题将焦点设置在列表框项目上会中断键盘导航
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();
}
回答by Jon C
You can't use Focus.() on a listbox item. However you can select items which is pretty much the same thing as you are looking to do. listbox.SelectedIndex = 0;
您不能在列表框项上使用 Focus.()。但是,您可以选择与您想要做的事情几乎相同的项目。 listbox.SelectedIndex = 0;

