Skip to content

Instantly share code, notes, and snippets.

@winkel
Last active December 18, 2015 10:40
Show Gist options
  • Save winkel/5055523 to your computer and use it in GitHub Desktop.
Save winkel/5055523 to your computer and use it in GitHub Desktop.
WinRT AttachedCommands
public static class AttachedCommands
{
public static readonly DependencyProperty ControlTappedCommandProperty =
DependencyProperty.RegisterAttached("ControlTappedCommand",
typeof(ICommand), typeof(AttachedCommands),
new PropertyMetadata(null, new PropertyChangedCallback(AttachOrRemoveUIElementTappedEvent)));
public static ICommand GetControlTappedCommand(DependencyObject obj)
{
return (ICommand)obj.GetValue(ControlTappedCommandProperty);
}
public static void SetControlTappedCommand(DependencyObject obj, ICommand value)
{
obj.SetValue(ControlTappedCommandProperty, value);
}
public static void AttachOrRemoveUIElementTappedEvent(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
UIElement uiElement = obj as UIElement;
if (uiElement != null)
{
ICommand cmd = (ICommand)args.NewValue;
if (args.OldValue == null && args.NewValue != null)
uiElement.Tapped += ExecuteUIElementTapped;
else if (args.OldValue != null && args.NewValue == null)
uiElement.Tapped -= ExecuteUIElementTapped;
}
}
private static void ExecuteUIElementTapped(object sender, TappedRoutedEventArgs e)
{
DependencyObject obj = sender as DependencyObject;
ICommand cmd = (ICommand)obj.GetValue(ControlTappedCommandProperty);
if (cmd != null)
{
if (cmd.CanExecute(obj))
cmd.Execute(obj);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment