Performing an action (Command) after pressing the Enter key in a WPF TextBox

Unfortunately the out-of-the-box implementation of WPF’s TextBox control has no built-in way to execute a ‘default’ ICommand action when the Enter key is pressed.  I took a first stab at this for my current client, and here is a rewritten/improved implementation of a “Commandable” TextBox:

/* Copyright (c) 2009 Giorgio Galante. 
* Released under the MIT License (http://en.wikipedia.org/wiki/MIT_License)
*/
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;

namespace WPFControls
{
public class CommandableTextBox : TextBox
{
public static readonly DependencyProperty
CommandProperty = DependencyProperty.Register(
"Command",
typeof (ICommand),
typeof (CommandableTextBox),
new UIPropertyMetadata(null));

public static DependencyProperty CommandParameterProperty =
DependencyProperty.Register(
"CommandParameter",
typeof (object),
typeof (CommandableTextBox),
null);

public CommandableTextBox()
{
KeyUp += KeyUpAction;
}

public ICommand Command
{
get { return (ICommand) GetValue(CommandProperty); }
set { SetValue(CommandProperty, value); }
}

public object CommandParameter
{
get { return GetValue(CommandParameterProperty); }

set { SetValue(CommandParameterProperty, value); }
}

private void KeyUpAction(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
if (Command != null)
{
BindingExpression be = GetBindingExpression(TextProperty);
if (be != null)
{
be.UpdateSource();
}
Command.Execute(CommandParameter);
}
}
}
}
}


Comments

Thank you! But maybe we

Thank you!

But maybe we should check command before executing?

private void KeyUpAction(object sender, KeyEventArgs e)
{
....

if (Command.CanExecute(CommandParameter))
{
Command.Execute(CommandParameter);
}
....
}

Re: Thank you! But maybe we

Great idea ;-) I'll update this post/attachment a bit later to reflect the check...

Thanks!