This is a mirror of official site: http://jasper-net.blogspot.com/

AttachedBehavior pattern sample

| Tuesday, March 1, 2011
The ClickBehavior is about the simplest I can think of.  For illustration purposes I only included one command, but LeftClickCommand, DoubleClickCommand, MouseOverCommand etc. are all obvious extensions:

 public static class ClickBehavior
   {
       public static DependencyProperty RightClickCommandProperty = DependencyProperty.RegisterAttached("RightClick",
                   typeof(ICommand),
                   typeof(ClickBehavior),
                   new FrameworkPropertyMetadata(null, new PropertyChangedCallback(ClickBehavior.RightClickChanged)));

       public static void SetRightClick(DependencyObject target, ICommand value)
       {
           target.SetValue(ClickBehavior.RightClickCommandProperty, value);
       }

       public static ICommand GetRightClick(DependencyObject target) {
           return (ICommand)target.GetValue(RightClickCommandProperty);
       }


       private static void RightClickChanged(DependencyObject target, DependencyPropertyChangedEventArgs e)
       {
           UIElement element = target as UIElement;
           if (element != null)
           {
               // If we're putting in a new command and there wasn't one already
               // hook the event
               if ((e.NewValue != null) && (e.OldValue == null))
               {
                   element.MouseRightButtonUp += element_MouseRightButtonUp;
               }
               // If we're clearing the command and it wasn't already null
               // unhook the event
               else if ((e.NewValue == null) && (e.OldValue != null))
               {
                   element.MouseRightButtonUp -= element_MouseRightButtonUp;
               }
           }
       }

       static void element_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
       {
           UIElement element = (UIElement)sender;
           ICommand command = (ICommand)element.GetValue(ClickBehavior.RightClickCommandProperty);
           command.Execute(null);
       }
   }
   public class DelegateCommand : ICommand
   {  
       public delegate void SimpleEventHandler();
       private SimpleEventHandler handler;
       private bool isEnabled = true;

       public event EventHandler CanExecuteChanged;

       public DelegateCommand(SimpleEventHandler handler)
       {
           this.handler = handler;
       }

       private void OnCanExecuteChanged()
       {
           if (this.CanExecuteChanged != null)
           {
               this.CanExecuteChanged(this, EventArgs.Empty);
           }
       }


Read more: Tales from the Smart Client

Posted via email from Jasper-net

0 comments: