Skip to content

Instantly share code, notes, and snippets.

@cmorgado
Created September 26, 2014 22:23
Show Gist options
  • Save cmorgado/0dfc133019dec3e8e46e to your computer and use it in GitHub Desktop.
Save cmorgado/0dfc133019dec3e8e46e to your computer and use it in GitHub Desktop.
Universal App behavior ... press enter to move focus to desired control
/// <summary>
/// <Interactivity:Interaction.Behaviors>
/// <MoreBehaviors:CommandOnEnterPressFocus Target="{Binding ElementName=yourothercontrol}" />
/// </Interactivity:Interaction.Behaviors>
/// </summary>
[Microsoft.Xaml.Interactivity.TypeConstraint(typeof(TextBox))]
class CommandOnEnterPressFocus : DependencyObject, IBehavior
{
public Windows.UI.Xaml.DependencyObject AssociatedObject { get; set; }
public static readonly DependencyProperty TargetProperty = DependencyProperty.Register("Target", typeof(Control), typeof(CommandOnEnterPressFocus), new PropertyMetadata(null));
/// <summary>
/// The focus target.
/// </summary>
public Control Target
{
get { return (Control)base.GetValue(TargetProperty); }
set { base.SetValue(TargetProperty, value); }
}
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)
{
if (Target != null)
{
Target.Focus(FocusState.Programmatic);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment