kidroca

Event As ICommand Using Attached Property

Dec 17th, 2015
166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.64 KB | None | 0 0
  1. namespace Attached.Behaviors.General
  2. {
  3.     using System.Windows.Input;
  4.     using Windows.UI.Xaml;
  5.     using Windows.UI.Xaml.Input;
  6.  
  7.     public class ElementTapGesture
  8.     {
  9.         public static readonly DependencyProperty TapItProperty =
  10.             DependencyProperty.RegisterAttached(
  11.             "TapCommand",
  12.             typeof(ICommand),
  13.             typeof(ElementTapGesture), // Changed from UIElement to this class, and now the code runs fine
  14.             new PropertyMetadata(null, TapChanged));
  15.  
  16.         public static void SetTapCommand(DependencyObject element, ICommand value)
  17.         {
  18.             element.SetValue(TapItProperty, value);
  19.         }
  20.  
  21.         public static ICommand GetTapCommand(DependencyObject element)
  22.         {
  23.             return (ICommand)element.GetValue(TapItProperty);
  24.         }
  25.  
  26.         private static void TapChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  27.         {
  28.             var element = d as UIElement;
  29.             if (element == null)
  30.             {
  31.                 return;
  32.             }
  33.  
  34.             if (e.NewValue != null)
  35.             {
  36.                 element.Tapped += OnElementTap;
  37.             }
  38.             else
  39.             {
  40.                 element.Tapped -= OnElementTap;
  41.             }
  42.         }
  43.  
  44.         private static void OnElementTap(object sender, TappedRoutedEventArgs e)
  45.         {
  46.             ICommand command = GetTapCommand(sender as DependencyObject);
  47.             if (command != null)
  48.             {
  49.                 if (command.CanExecute(e))
  50.                 {
  51.                     command.Execute(e);
  52.                 }
  53.             }
  54.         }
  55.     }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment