如何在 WPF 中移动焦点?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15587649/
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 move focus in WPF?
提问by Smith
I wonder if there is anyway to change focus from the current control and move it to other control in WPF on TabIndex assigned controls.
我想知道是否有任何方法可以将焦点从当前控件更改为 WPF 中 TabIndex 分配控件上的其他控件。
Example I have controls with TabIndex 1 to 5, is there a way to jumb the focus from 1 to 5 ?
示例我有 TabIndex 1 到 5 的控件,有没有办法将焦点从 1 跳转到 5 ?
<TextBox TabIndex="1" Focusable = "true" LostFocus="test_LostFocus"/>
<TextBox TabIndex="2" Focusable = "true"/>
...
<TextBox TabIndex="5" Focusable = "true" name="LastControl"/>
.
.
private void test_LostFocus(object sender, RoutedEventArgs e)
{
LastControl.Focus();
}
I tried Keyboard.Focus()and FocusManager.SetFocusedElement()but no luck.
我试过了 Keyboard.Focus(),FocusManager.SetFocusedElement()但没有运气。
Any idea?
任何的想法?
采纳答案by keyboardP
Simply handle the KeyDownevent for the textboxes and set focus there. Since you're using Tab, let the control know you'll handle it by setting e.Handled = true, which will stop the default tabaction of jumping to the control with the next TabIndex.
只需处理KeyDown文本框的事件并在那里设置焦点。由于您正在使用Tab,请让控件知道您将通过设置来处理它e.Handled = true,这将停止使用下tab一个TabIndex.
private void tb_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Tab)
{
e.Handled = true;
LastControl.Focus();
}
}
回答by Blachshma
As stated in the comments, KeyDownis a better way to go (lostfocus will cause weird behaviors such as the user specifically clicking on the second control and the focus goes to the last one instead)...
正如评论中所述,KeyDown是一种更好的方法(lostfocus 会导致奇怪的行为,例如用户专门单击第二个控件而焦点转到最后一个控件)...
Make sure you set the e.Handledto true though..!
确保你设置e.Handled为 true ..!
This will work:
这将起作用:
private void TextBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Tab)
{
e.Handled = true;
LastControl.Focus();
}
}
Where the deceleration of the textbox should be something like this:
文本框的减速应该是这样的:
<TextBox TabIndex="1" Focusable = "true" KeyDown="TextBox1_KeyDown"/>

