Friday, December 9, 2011

WPF : Creating a Behavior for a TextBox which invokes a command when Enter key is pressed



Goal :  Execute a command when an enter key is pressed ,while focus is in a text-box.  This command can be a command bounded to a Button or any UI element.
Look at following code
Here I am going to create an attached property of ICommand type, which would be applied to TextBoxes. While that property is getting attached to a TextBox, I register an EventHandler for KeyUp event and in that I check for Enter key cod, if it matches I execute attached command property for that object.

/// <summary>
/// EnterKeyCommand Attached Dependency Property
/// </summary>
public static readonly DependencyProperty EnterKeyCommandProperty =
DependencyProperty.RegisterAttached("EnterKeyCommand"typeof(ICommand), typeof(TextBoxBehaviours), new FrameworkPropertyMetadata(null, new PropertyChangedCallback(OnEnterKeyCommandChanged)));
 
/// <summary>
/// Gets the EnterKeyCommand property. This dependency property 
/// indicates ....
/// </summary>
public static ICommand GetEnterKeyCommand(DependencyObject d)
{
 return (ICommand)d.GetValue(EnterKeyCommandProperty);
}
 
/// <summary>
/// Sets the EnterKeyCommand property. This dependency property 
/// indicates ....
/// </summary>
public static void SetEnterKeyCommand(DependencyObject d, ICommand value)
{
 d.SetValue(EnterKeyCommandProperty, value);
}
 
/// <summary>
/// Handles changes to the EnterKeyCommand property.
/// </summary>
private static void OnEnterKeyCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
 ICommand oldEnterKeyCommand = (ICommand)e.OldValue;
 ICommand newEnterKeyCommand = (ICommand)d.GetValue(EnterKeyCommandProperty);
 if (d is TextBox )
 {
   (d as TextBox).KeyUp += new KeyEventHandler(TextBoxBehaviours_KeyUp);
 }
}

No comments:

Post a Comment