Executing viewmodels command on enter in TextBox

后端 未结 5 1358
深忆病人
深忆病人 2020-12-24 00:23

I want to execute a command in my viewmodel when the user presses enter in a TextBox. The command works when bound to a button.

5条回答
  •  北海茫月
    2020-12-24 00:55

    In addition to Mark Heath's answer, I took the class one step further by implementing Command Parameter attached property in this way;

    public static class EnterKeyHelpers
    {
            public static ICommand GetEnterKeyCommand(DependencyObject target)
            {
                return (ICommand)target.GetValue(EnterKeyCommandProperty);
            }
    
            public static void SetEnterKeyCommand(DependencyObject target, ICommand value)
            {
                target.SetValue(EnterKeyCommandProperty, value);
            }
    
            public static readonly DependencyProperty EnterKeyCommandProperty =
                DependencyProperty.RegisterAttached(
                    "EnterKeyCommand",
                    typeof(ICommand),
                    typeof(EnterKeyHelpers),
                    new PropertyMetadata(null, OnEnterKeyCommandChanged));
    
    
            public static object GetEnterKeyCommandParam(DependencyObject target)
            {
                return (object)target.GetValue(EnterKeyCommandParamProperty);
            }
    
            public static void SetEnterKeyCommandParam(DependencyObject target, object value)
            {
                target.SetValue(EnterKeyCommandParamProperty, value);
            }
    
            public static readonly DependencyProperty EnterKeyCommandParamProperty =
                DependencyProperty.RegisterAttached(
                    "EnterKeyCommandParam",
                    typeof(object),
                    typeof(EnterKeyHelpers),
                    new PropertyMetadata(null));
    
            static void OnEnterKeyCommandChanged(DependencyObject target, DependencyPropertyChangedEventArgs e)
            {
                ICommand command = (ICommand)e.NewValue;
                Control control = (Control)target;
                control.KeyDown += (s, args) =>
                {
                    if (args.Key == Key.Enter)
                    {
                        // make sure the textbox binding updates its source first
                        BindingExpression b = control.GetBindingExpression(TextBox.TextProperty);
                        if (b != null)
                        {
                            b.UpdateSource();
                        }
                        object commandParameter = GetEnterKeyCommandParam(target);
                        command.Execute(commandParameter);
                    }
                };
            }
        } 
    

    Usage:

    
    

提交回复
热议问题