4

在文本框输入中。输入回车键后,我想隐藏软键盘。如何在代码中做到这一点?

private void OnKeyDownHandler(object sender, KeyEventArgs e)
           {
                if (e.Key != Key.Enter)
                   return;         

...}
4

2 回答 2

27

this.focus() 这将使焦点从文本框中丢失。它基本上将焦点放在页面上。您还可以将文本框转换为read only以禁止任何进一步的输入。

隐藏 SIP 可以通过简单地将焦点从文本框更改到页面上的任何其他元素来完成。它不一定是 this.focus(),它可以是 anyElement.focus()。只要元素不是您的文本框,SIP 就应该隐藏自己。

于 2011-11-01T03:02:11.013 回答
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();
        }
    }
 }

The Ancestors method comes from LinqToVisualTree by Colin Eberhardt. The code is used in conjunction with an Enter key handler, for "tabbing" to the next TextBox or PasswordBox, which is why they're skipped in the selection, but you could include them if it makes sense for you.

于 2011-11-01T08:32:39.907 回答