【发布时间】:2014-10-24 15:44:12
【问题描述】:
我想要的是当用户按下回车键时当前聚焦的文本框何时失去焦点。我认为实现这一点的唯一方法是使用 XAML 中的输入绑定绑定到代码中的命令,该代码将整个文本框控件传递给视图模型。我不喜欢这种方法,并希望有人有一种“干净”的方法来解决这个问题。
【问题讨论】:
我想要的是当用户按下回车键时当前聚焦的文本框何时失去焦点。我认为实现这一点的唯一方法是使用 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();
}
}
然后,只需在您想要特定行为的任何地方使用您的自定义文本框。
【讨论】:
您经常在登录时得到一个密码框,您需要允许输入键。
<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>
【讨论】: