2012-08-26 18 views
1

奇怪的行爲!當我點擊地鐵應用程序上的按鈕時效果很好,但是當我點擊進入(KB上的按鈕)時,唯一發生的事情就是一切都被清除了!2種類型的點擊事件相同的代碼2導致winrt

這種失敗

private void TextBox_KeyDown_1(object sender, KeyRoutedEventArgs e) 
    { 
     if (e.Key == VirtualKey.Enter) 
     { 
      textBlock.Text = textBox1.Text; 
      // textBox1.Text = ""; 
     } 
    } 

可正常工作

private void Send_Click(object sender, RoutedEventArgs e) 
    { 

     textBlock.Text = textBox1.Text; 
     textBox1.Text = ""; 
    } 

我在做什麼錯?

感謝

+0

你有AcceptButton屬性集嗎?你有KeyPreview設置爲真? –

回答

1

這將是最好的,如果按下回車鍵的文本框時,它會actualy模擬按鈕點擊,以確保這兩個操作實際上是一樣的。

private void TextBox_KeyDown_1(object sender, KeyRoutedEventArgs e) 
{ 
    if (e.Key == VirtualKey.Enter) 
    { 
     this.Send.PerformClick(); 
    } 
} 

private void Send_Click(object sender, RoutedEventArgs e) 
{ 
    textBlock.Text = textBox1.Text; 
    textBox1.Text = ""; 
} 

此外,克里斯提到的,你真的不應該處理的KeyDown即使在這種情況下:您可以設置窗體的AcceptButton屬性爲發送按鈕,這意味着,當按下Enter鍵,按鈕將被按下 - 即使沒有集中。這種問題是爲什麼使用AcceptButton屬性的一個很好的例子。

0

我認爲你正在嘗試處理焦點時,用戶點擊回車。這是應用程序中的常見要求。至於你的奇怪行爲,我無法解釋它。但我也不確定解釋它與解決問題一樣重要。所以,我可以告訴你的易於實現的操作輸入和重點:

<StackPanel> 
    <TextBlock FontSize="20" Foreground="White">One</TextBlock> 
    <TextBox x:Name="T1" Width="1000" Height="100" KeyDown="T1_KeyDown_1" /> 
    <TextBlock FontSize="20" Foreground="White">Two</TextBlock> 
    <TextBox x:Name="T2" Width="1000" Height="100" KeyDown="T2_KeyDown_1" /> 
</StackPanel> 

private void T1_KeyDown_1(object sender, KeyRoutedEventArgs e) 
{ 
    if (e.Key == Windows.System.VirtualKey.Enter) 
     T2.Focus(Windows.UI.Xaml.FocusState.Programmatic); 
} 

private void T2_KeyDown_1(object sender, KeyRoutedEventArgs e) 
{ 
    if (e.Key == Windows.System.VirtualKey.Enter) 
     T1.Focus(Windows.UI.Xaml.FocusState.Programmatic); 
} 

結果是完美的對焦控制。

相關問題