Last active
December 18, 2015 10:40
-
-
Save winkel/5055523 to your computer and use it in GitHub Desktop.
WinRT AttachedCommands
This file contains hidden or 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
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