2013-07-03 65 views
3

我有一個基本的登錄頁面,如何使用回車鍵提交登錄信息

<TextBox x:Name="UsernameInput" HorizontalAlignment="Left" TextWrapping="Wrap" Text="{Binding Username, Mode=TwoWay}" VerticalAlignment="Center" Grid.Row="0" Grid.Column="2" Width="400" /> 
    <PasswordBox HorizontalAlignment="Left" VerticalAlignment="Center" Password="{Binding Password, Mode=TwoWay}" Grid.Row="1" Grid.Column="2" Width="400"/> 
    <TextBlock HorizontalAlignment="Right" TextWrapping="Wrap" Text="Username: " VerticalAlignment="Center" Margin="0,0,0,15" Grid.Row="0" Grid.Column="0" Style="{StaticResource SubheaderTextStyle}"/> 
    <TextBlock HorizontalAlignment="Right" TextWrapping="Wrap" Text="Password: " VerticalAlignment="Center" Margin="0,0,0,15" Grid.Row="1" Grid.Column="0" Style="{StaticResource SubheaderTextStyle}"/> 

    <Button Content="Login" HorizontalAlignment="Center" VerticalAlignment="Center" Grid.Row="2" Grid.Column="2" Height="50" Width="300" Command="{Binding LoginCommand}"/> 

我如何可以模擬「登錄」按鈕,如果用戶點擊從密碼字段中的回車鍵被按下?

謝謝!

回答

8

您可以使用KeyDown事件PasswordBox

<PasswordBox KeyDown="txtPassword_KeyDown"/> 

private void txtPassword_KeyDown(object sender, KeyRoutedEventArgs e) 
{ 
    if (e.Key == Windows.System.VirtualKey.Enter) 
     //TODO: do login 
} 
+1

是的。好答案。請記住儘管驗證輸入! –

1

使用在PasswordBox的KeyDown事件 -

<PasswordBox KeyDown="PasswordKeyDown"/> 

然後在你的C#代碼檢查,如果輸入鍵被按下,並相應地登錄:

using System.Windows.Input; 

private void PasswordKeyDown(object sender, KeyEventArgs e) 
{ 
    if (e.Key == Key.Enter) 
     Login(); 
} 
+0

我得到的錯誤,KeyEventArgs不包含「密鑰」的定義 –

+0

您使用WPF或窗體KeyEventArgs?請確保您使用System.Windows.Input,更多信息在這裏:http://msdn.microsoft.com/en-us/library/system.windows.input.keyeventargs.aspx – Sherlock

+0

你有沒有得到這個工作馬蒂? – Sherlock