Invoke Command When “ENTER” Key Is Pressed In XAML

后端 未结 5 409
花落未央
花落未央 2020-12-24 08:38

I want to invoke a command when ENTER is pressed in a TextBox. Consider the following XAML:



        
5条回答
  •  有刺的猬
    2020-12-24 09:03

    I ran into this same issue yesterday and solved it using custom triggers. It may seem a bit much at first, but I found this general pattern is usable for doing a lot of the things that I used to accomplish using event handlers directly in a view (like double click events). The first step is to create a trigger action that can accept a parameter since we will need it later.

    public class ExecuteCommandAction : TriggerAction
    {
        public string Command { get; set; }
    
        protected override void Invoke(object o)
        {
            if (Command != null)
            {
                object ctx = AssociatedObject.DataContext;
                if (ctx != null)
                {
                    var cmd = ctx.GetType().GetProperty(Command)
                        .GetValue(ctx, null) as ICommand;
                    if (cmd != null && cmd.CanExecute(o))
                    {
                        cmd.Execute(o);
                    }
                }
            }
        }
    }
    

    The next step is to create the trigger. You could do some interesting things with base classes to make it more generic for capturing different types of key presses, but we'll keep it simple.

    public class TextBoxEnterKeyTrigger: TriggerBase
    {
        protected override void OnAttached()
        {
            base.OnAttached();
            AssociatedObject.KeyUp += AssociatedObject_KeyUp;
        }
    
        protected override void OnDetaching()
        {
            base.OnDetaching();
            AssociatedObject.KeyUp -= AssociatedObject_KeyUp;
        }
    
        void AssociatedObject_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                TextBox textBox = AssociatedObject as TextBox;
                object o = textBox == null ? null : textBox.Text;
                if (o != null)
                {
                    InvokeActions(o);
                }
            }
        }
    }
    

    Keep in mind that even though you may have a data binding in place to your TextBox value, the property changed event won't fire because your textbox hasn't lost focus. For this reason I am passing the value of the TextBox.Text property to the command. The last step is to use this feature in your XAML. You need to be sure to include the Interactivity namespace as well as the namespace that contains your code from above.

    
        
            
                
                    
                
            
        
    
    

提交回复
热议问题