有几种方法可以解决这个问题。第一种方法更适合 MVVM,我们只检测到绑定到您的 TextBox 的 Text 的值发生变化:
在 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>
编辑
此外,您还可以绑定到文本框上的 KeyBinding 命令:
<TextBox AcceptsReturn="False">
<TextBox.InputBindings>
<KeyBinding
Key="Enter"
Command="{Binding SearchCommand}"
CommandParameter="{Binding Path=Text, RelativeSource={RelativeSource AncestorType={x:Type TextBox}}}" />
</TextBox.InputBindings>
另一种选择是在视图中继续处理 KeyDown 事件,但在代码隐藏中调用 ViewModel 方法: