簡體   English   中英

WPF MVVM在Enter鍵上取消選擇文本框

[英]WPF MVVM deselect textbox on Enter key press

我想要的是當用戶按下Enter鍵時當前焦點對准的文本框失去焦點的時候。 我能想到的唯一方法是使用XAML中的輸入綁定將代碼綁定到將整個文本框控件傳遞到視圖模型的代碼中的命令。 我不喜歡這種方法,希望有人能夠以一種“干凈”的方式解決這個問題。

您可以創建一個自定義文本框,並將其放入控件代碼中:

public partial class CustomTextBox : TextBox
{
    public CustomTextBox()
    {
        InitializeComponent();
    }

    protected override void OnKeyDown(KeyEventArgs e)
    {
        base.OnKeyDown(e);
        if(e.Key == Key.Return)
        Keyboard.ClearFocus();
    }
}

然后,只需在需要該特定行為的地方使用自定義文本框即可。

通常,您在登錄時會看到一個密碼框,您需要允許輸入Enter鍵。

<PasswordBox VerticalAlignment="Center" x:Name="txtPassword" Template="{StaticResource PassBoxBaseControlTemplate}" Height="25" BorderBrush="Black" Width="165.031">
   <PasswordBox.InputBindings>
        <KeyBinding Key="Enter" Command="{Binding ComLoginClickOK}" CommandParameter="{Binding ElementName=txtPassword}"/>
   </PasswordBox.InputBindings>
</PasswordBox>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM