按下回车键时在文本框上执行命令

3

我刚接触WPF,发现最好的模式是MVVM。我试图深入了解它,发现命令只能在按钮、菜单项等上执行。但我有一个疑问,当我聚焦于文本框并完成编辑后,如何执行ViewModel命令以按下回车键。

我已经搜索了谷歌,但所有答案都无济于事。所以希望大家帮助我。如何在文本框中按下回车键时执行命令?


请查看这里 https://dev59.com/knA75IYBdhLWcg3wOGPS - undefined
我猜你想要的是一个附加的行为,当你按下回车键时,文本框的Text属性会更新:https://dev59.com/pXRB5IYBdhLWcg3wpYmo#564659(同时请阅读该答案的评论)。我想不需要命令。 - user2819245
2个回答

10
在我看来,最简单的方法是使用KeyBinding,它允许你将KeyGesture绑定到一个ICommand实现。在你的情况下,你可以在XAML中编写类似于以下内容的代码:
<TextBox AcceptsReturn="False">
    <TextBox.InputBindings>
        <KeyBinding Key="Enter" Command="{Binding YourCommand}" />
    </TextBox.InputBindings>
</TextBox>

当你的TextBox被聚焦并且你按下Enter键时,YourCommand将被执行。
希望它能对你有所帮助。

2
你可以在WPF中使用行为来实现你的需求。
在XAML中,
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>

在 ViewModel.cs 文件中,
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
    }

}

这将在文本框中输入的每个字符上执行命令,而 OP 只需要在按下回车键时执行。 - undefined
他可以通过使用TextBox中的Focused和UnFocused事件来实现他的需求,而不是使用TextChanged事件。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接