Search code examples
c#wpfkey-bindings

Programmatically create a key binding for textbox input


While searching this site, I've found this post Create a simple, unmodified key binding in WPF which shows how to bind a simple command to the a key. However I require a bit more than this. I'd like to also set a parameter to this command. A parameter which is will be bound to a text box, I use for input. Here's the code I have:

var textBinding = new Binding("Text") { Source = textBoxInput };
            buttonConfirmAddKitType.SetBinding(ButtonBase.CommandParameterProperty, textBinding);
            var keybinding = new KeyBinding
                                        {
                                            Key = Key.Enter,
                                            Command = command,
                                        };
            //Here I need a way to set the source of the command to the text of the input textbox, as done above
            textBoxInput.InputBindings.Add(keybinding);

The only missing piece here is how to bind the parameter of the key binding's command to the text of my textbox, and I cant seem to find the answer anywhere. Help would be appreciated.


Solution

  •         var textBinding = new Binding("Text") { Source = textBoxInput };
            buttonConfirmAddKitType.SetBinding(ButtonBase.CommandParameterProperty, textBinding);
            var keybinding = new KeyBinding
            {
                Key = Key.Enter,
                Command = command,
            };
            keybinding.CommandParameter = textBoxInput.Text;
            textBoxInput.InputBindings.Add(keybinding);