在TextBox输入中。 输入密钥后,我想隐藏软键盘。 如何在代码中执行此操作?
private void OnKeyDownHandler(object sender, KeyEventArgs e)
{
if (e.Key != Key.Enter)
return;
...}
答案 0 :(得分:27)
this.focus()
这将允许焦点从文本框中丢失。它基本上把重点放在页面上。您也可以将文本框转换为read only
以禁止任何进一步的输入。
隐藏SIP可以通过简单地将焦点从文本框更改为页面上的任何其他元素来完成。它不一定是this.focus(),它可以是anyElement.focus()。只要该元素不是您的文本框,SIP就应该隐藏自己。
答案 1 :(得分:2)
我使用以下方法来关闭SIP:
///
/// Dismisses the SIP by focusing on an ancestor of the current element that isn't a
/// TextBox or PasswordBox.
///
public static void DismissSip()
{
var focused = FocusManager.GetFocusedElement() as DependencyObject;
if ((null != focused) && ((focused is TextBox) || (focused is PasswordBox)))
{
// Find the next focusable element that isn't a TextBox or PasswordBox
// and focus it to dismiss the SIP.
var focusable = (Control)(from d in focused.Ancestors()
where
!(d is TextBox) &&
!(d is PasswordBox) &&
d is Control
select d).FirstOrDefault();
if (null != focusable)
{
focusable.Focus();
}
}
}
Ancestors
方法来自Colin Eberhardt的LinqToVisualTree。该代码与Enter键处理程序一起使用,用于“tabbing”到下一个TextBox或PasswordBox,这就是为什么它们在选择中被跳过的原因,但如果它对你有用,你可以包括它们。