【问题标题】:WPF MVVM deselect textbox on Enter key pressWPF MVVM在Enter键按下时取消选择文本框
【发布时间】:2014-10-24 15:44:12
【问题描述】:

我想要的是当用户按下回车键时当前聚焦的文本框何时失去焦点。我认为实现这一点的唯一方法是使用 XAML 中的输入绑定绑定到代码中的命令,该代码将整个文本框控件传递给视图模型。我不喜欢这种方法,并希望有人有一种“干净”的方法来解决这个问题。

【问题讨论】:

    标签: c# wpf mvvm prism


    【解决方案1】:

    您可以创建一个自定义文本框并将其放入控件代码中:

    public partial class CustomTextBox : TextBox
    {
        public CustomTextBox()
        {
            InitializeComponent();
        }
    
        protected override void OnKeyDown(KeyEventArgs e)
        {
            base.OnKeyDown(e);
            if(e.Key == Key.Return)
            Keyboard.ClearFocus();
        }
    }
    

    然后,只需在您想要特定行为的任何地方使用您的自定义文本框。

    【讨论】:

    • 这实际上可能比我计划的方式更好。谢谢,一旦我有机会玩它,我会标记它。
    • 需要注意的是 KeyBoard.ClearFocus 适用于 .Net 4.0,因此如果您使用的是旧版本,请查看此线程:stackoverflow.com/questions/2914495/…
    【解决方案2】:

    您经常在登录时得到一个密码框,您需要允许输入键。

    <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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-11-06
      • 1970-01-01
      • 2010-10-23
      • 1970-01-01
      • 2012-12-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多