在我的 ViewModel 中,如何检测在文本框中输入文本时按下了什么键?
在普通的 WPF/C# 中,我正在这样做......
XAML 文件
<TextBox x:Name="myInputField" KeyDown="inputField_KeyDown"/>
代码隐藏 .xaml.cs
private void inputField_KeyDown(object sender, KeyEventArgs e)
{
if (Keyboard.IsKeyDown(Key.Enter)) {
// do something
}
}
编辑:
仅供引用 - 我想要做的是为回车键创建一个快捷方式。
最佳答案
有几种方法可以解决这个问题。第一种方法更适合 MVVM,我们只检测到 Text
值的变化。绑定(bind)到您的TextBox
:
在 XAML 中:
<TextBox x:Name="myInputField",
Text="{Binding MyText, UpdateSourceTrigger=PropertyChanged}" />
在虚拟机中
private string myText;
public string MyText
{
get
{
return myText;
}
set
{
if (Set(nameof (MyText), ref myText, value))
{
// the value of the text box changed.. do something here?
}
}
}
或者,为了更直接地回答您提出的问题,如果您必须依靠检测文本框中的按键,您应该利用
EventToCommand
that you can hook in with MVVMLight在 XAML 中:
xmlns:cmd="http://www.galasoft.ch/mvvmlight"
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
...
<TextBox ....
<i:Interaction.Triggers>
<i:EventTrigger EventName="KeyDown">
<cmd:EventToCommand Command="{Binding RelativeSource={RelativeSource AncestorType={x:Type UserControl}}, Path=DataContext.KeyDownCommand}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</TextBox>
编辑
此外,您还可以绑定(bind)到文本框上的 KeyBinding 命令:
<TextBox AcceptsReturn="False">
<TextBox.InputBindings>
<KeyBinding
Key="Enter"
Command="{Binding SearchCommand}"
CommandParameter="{Binding Path=Text, RelativeSource={RelativeSource AncestorType={x:Type TextBox}}}" />
</TextBox.InputBindings>
另一种选择是继续在 View 中处理 KeyDown 事件,但在代码隐藏中调用 ViewModel 方法:
关于c# - 如何使用 MVVM Light 检测 TextBox 中的按键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47128393/