2011-11-01 102 views
4

在TextBox輸入中。 鍵入確認鍵後,我想隱藏軟鍵盤。 如何在代碼中做到這一點?如何隱藏WP7中的軟鍵盤?

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

...} 

回答

27

this.focus() 這將允許從文本框失去焦點。它基本上把重點放在頁面上。您也可以將您的文本框轉換爲read only以禁止進一步輸入。

隱藏SIP可以通過將焦點從文本框更改爲頁面上的任何其他元素來完成。它不一定是this.focus(),它可以是anyElement.focus()。只要該元素不是您的文本框,SIP應該隱藏自己。

+0

謝謝。但我無法使用它。因爲我只找到this.SearchTxt.Focus()這意味着獲得焦點。但TextBox沒有設置焦點。 – whi

+0

那麼,只需將焦點從文本框更改爲頁面上的任何其他元素即可隱藏SIP。它不必是'this.focus()',它可以是'anyElement.focus()'。只要該元素不是您的文本框,SIP應該隱藏自己。 – abhinav

+0

Got it!它的工作原理,謝謝。 – whi

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方法來自LinqToVisualTree科林·埃伯哈特。該代碼與Enter鍵處理程序一起使用,用於「Tabbing」到下一個TextBox或PasswordBox,這就是爲什麼它們在選擇中被跳過的原因,但如果它適合您,則可以包含它們。