我刚接触WPF,发现最好的模式是MVVM。我试图深入了解它,发现命令只能在按钮、菜单项等上执行。但我有一个疑问,当我聚焦于文本框并完成编辑后,如何执行ViewModel命令以按下回车键。
我已经搜索了谷歌,但所有答案都无济于事。所以希望大家帮助我。如何在文本框中按下回车键时执行命令?
<TextBox AcceptsReturn="False">
<TextBox.InputBindings>
<KeyBinding Key="Enter" Command="{Binding YourCommand}" />
</TextBox.InputBindings>
</TextBox>
TextBox
被聚焦并且你按下Enter键时,YourCommand
将被执行。xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
<TextBox Text="MyText">
<i:Interaction.Behaviors>
<i:BehaviorCollection>
<EventToCommand EventName="TextChanged" Command="{Binding ViewModelCommand}">
**// You can provide other events to be triggered in the EventName property based on your requirement like "Focused" or "UnFocused".Focused event will be fired if you enter into edit mode and UnFocused event will be triggered if you press enter key.**
<i:BehaviorCollection>
</i:Interaction.Behaviors>
</TextBox>
Public class ViewModel
{
private Command viewCommand;
public ViewModel()
{
viewCommand = new Command(CommandMethod);
}
public Command ViewModelCommand
{
get { return viewCommand }
set { viewCommand = value}
}
private void CommandMethod()
{
//This method will hit if you modify enter/delete text in the TextBox
}
}
Text
属性会更新:https://dev59.com/pXRB5IYBdhLWcg3wpYmo#564659(同时请阅读该答案的评论)。我想不需要命令。 - user2819245