Created
September 26, 2014 22:25
-
-
Save cmorgado/2cf5cd514458ddc9fd8e to your computer and use it in GitHub Desktop.
Universal App Behavior: press enter on texbox and execute your command
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// <Interactivity:Interaction.Behaviors> | |
/// <MoreBehaviors:CommandOnEnterPress Command="{Binding DoYourCommand}" /> | |
/// </Interactivity:Interaction.Behaviors> | |
/// </summary> | |
[Microsoft.Xaml.Interactivity.TypeConstraint(typeof(TextBox))] | |
class CommandOnEnterPress : DependencyObject, IBehavior | |
{ | |
[Microsoft.Xaml.Interactivity.CustomPropertyValueEditor(Microsoft.Xaml.Interactivity.CustomPropertyValueEditor.PropertyBinding)] | |
public ICommand Command | |
{ | |
get { return (ICommand)GetValue(CommandProperty); } | |
set { SetValue(CommandProperty, value); } | |
} | |
public static readonly DependencyProperty CommandProperty = | |
DependencyProperty.Register("Command", typeof(ICommand), typeof(CommandOnEnterPress), null); | |
[Microsoft.Xaml.Interactivity.CustomPropertyValueEditor(Microsoft.Xaml.Interactivity.CustomPropertyValueEditor.PropertyBinding)] | |
public object CommandParameter | |
{ | |
get { return (object)GetValue(CommandParameterProperty); } | |
set { SetValue(CommandParameterProperty, value); } | |
} | |
public static readonly DependencyProperty CommandParameterProperty = | |
DependencyProperty.Register("CommandParameter", typeof(object), typeof(CommandOnEnterPress), null); | |
public Windows.UI.Xaml.DependencyObject AssociatedObject { get; set; } | |
public void Attach(Windows.UI.Xaml.DependencyObject associatedObject) | |
{ | |
this.AssociatedObject = associatedObject; | |
var textbox = this.AssociatedObject as TextBox; | |
textbox.KeyDown += textbox_KeyDown; | |
} | |
public void Detach() | |
{ | |
var textbox = this.AssociatedObject as TextBox; | |
textbox.KeyDown -= textbox_KeyDown; | |
} | |
void textbox_KeyDown(object sender, Windows.UI.Xaml.Input.KeyRoutedEventArgs e) | |
{ | |
if (e.Key == Windows.System.VirtualKey.Enter | |
&& this.Command != null) | |
this.Command.Execute(this.CommandParameter); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment