【问题标题】:Execute command on textbox when hit enter key按回车键时在文本框上执行命令
【发布时间】:2017-05-21 07:26:06
【问题描述】:

我是 WPF 新手,我看到了最好的模式调用 MVVM。我尝试深入研究,发现该命令只能在按钮或菜单项等上执行。但是当我专注于文本框并按下回车键时,我怀疑如何执行 ViewModel 命令完成我的编辑。 我有谷歌这个,但我从所有这些答案中一无所获。所以希望大家帮助我。在文本框中按回车键如何执行命令?

【问题讨论】:

标签: c# wpf xaml mvvm


【解决方案1】:

在我看来,最简单的方法是使用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 只需要在输入时
    • 他可以使用 TextBox 中的 Focused 和 UnFocused 事件而不是 TextChanged 事件来实现他的要求
    猜你喜欢
    • 2013-11-27
    • 2013-11-18
    • 2013-03-07
    • 1970-01-01
    • 2015-01-17
    • 1970-01-01
    • 2011-06-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多