[英]How to move focus in WPF?
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?任何想法?
As stated in the comments, KeyDown
is 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
是一种更好的方法(失去焦点会导致奇怪的行为,例如用户专门单击第二个控件,焦点转到最后一个控件)...
Make sure you set the e.Handled
to 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"/>
Simply handle the KeyDown
event for the textboxes and set focus there.只需处理文本框的KeyDown
事件并在那里设置焦点。 Since you're using Tab
, let the control know you'll handle it by setting e.Handled = true
, which will stop the default tab
action of jumping to the control with the next TabIndex
.由于您使用的是Tab
,因此让控件知道您将通过设置e.Handled = true
来处理它,这将停止使用下一个TabIndex
跳转到控件的默认tab
操作。
private void tb_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Tab)
{
e.Handled = true;
LastControl.Focus();
}
}
Possible WPF answer, non-programmatic:可能的 WPF 答案,非编程:
Ctrl+Tab
/ Ctrl+Shift+Tab
Ctrl+Tab
/ Ctrl+Shift+Tab
Possible WPF answer, programmatic:可能的 WPF 答案,编程:
System.Windows.Forms.SendKeys.SendWait("^{TAB}");
/ /
System.Windows.Forms.SendKeys.SendWait("^+{TAB}");
https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.sendkeys.send https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.sendkeys.send
https://stackoverflow.com/a/15621425/10789707 https://stackoverflow.com/a/15621425/10789707
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.