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
Cheap Jordans
Do you know about Cheap Jordans? Many good feedbacks about this kind of shoes from customers, they say it's not only very comfortable but the lowest price. If you are rich interested in buying shoes and willing to make your foot feeling comfortable, please click here Cheap Jordans or Cheap Jordan Shoes to visit our website, you will see all kind types of shoes you deeply love.Thank you for coming!
supra skylow
Do you like supra skylow shoes? If you are rich interested in buying shoes, I recommend you to click here supra skylow to visit our website to see all kinds of shoes you deeply love.Thank you for coming!
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!
Nice work
Thanks! //Peter