views:

81

answers:

1

How to respond to Drag/Drop events of a usercontrol by usinng the commands pattern?

A: 

On the User Control

Implement a command that has a parameter. I use ICommand with Josh Smiths RelayCommand, but i extend it to give it a parameter. (code at the end of this answer)

  /// <summary>
  /// Gets and Sets the ICommand that manages dragging and dropping.
  /// </summary>
  /// <remarks>The CanExecute will be called to determin if a drop can take place, the Executed is called when a drop takes place</remarks>
  public ICommand DragDropCommand {
     get { return (ICommand)GetValue(DragDropCommandProperty); }
     set { SetValue(DragDropCommandProperty, value); }

now you can bind your view model to this command.

set another property for our entity drag type (you could hard code this) but i reuse this user control for different things and i dont want one control to accept the wrong entity type on a drop.

  /// <summary>
  /// Gets and Sets the Name of the items we are dragging
  /// </summary>
  public String DragEntityType {
     get { return (String)GetValue(DragEntityTypeProperty); }
     set { SetValue(DragEntityTypeProperty, value); }
  }

Override the OnPreviewLeftMouseButtonDown

   protected override void OnPreviewMouseLeftButtonDown(MouseButtonEventArgs e) {
      //find the item the mouse is over, i.e. the one you want to drag.
      var itemToDrag = FindItem(e);

      //move the selected items, using the drag entity type
      DataObject data = new DataObject(this.DragEntityType, itemToDrag);
      //use the helper class to initiate the drag
      DragDropEffects de = DragDrop.DoDragDrop(this, data, DragDropEffects.Move);

      //call the base
      base.OnPreviewMouseLeftButtonDown(e);
   }

when you call DragDrop.DoDragDrop, the below methods will be called at the approriate time

Override the OnDragOver and OnDragDrop methods, and use a command to ask if we can drag and we can drop

protected override void OnDragOver(DragEventArgs e) {

     //if we can accept the drop
     if (this.DragDropCommand != null && this.DragDropCommand.CanExecute(e.Data)) {

        // Console.WriteLine(true);
     }
     //otherwise
     else {
        e.Effects = DragDropEffects.None;
        e.Handled = true;
     }
     base.OnDragOver(e);
  }

  protected override void OnDrop(DragEventArgs e) {

     if (this.DragDropCommand == null) { }
     //if we dont allow dropping on ourselves and we are trying to do it
     //else if (this.AllowSelfDrop == false && e.Source == this) { }
     else {
        this.DragDropCommand.Execute(e.Data);
     }
     base.OnDrop(e);
  }

In the View Model

then when you are setting up your command in the view model use something like this, then bind the command to your user control

     this.MyDropCommand = new ExtendedRelayCommand((Object o) => AddItem(o), (Object o) => { return ItemCanBeDragged(o); });

usually you are dragging from one user control to another so you would set up one command for one user control and one for the other, each having a different DragEntityType that you would accept. Two user controls one to drag from, one to drop on, and vica versa. each user control has a different DragEntityType so you can tell which one the drag originated from.

  private Boolean ItemCanBeDragged(object o) {
     Boolean returnValue = false;

     //do they have permissions to dragt
     if (this.HasPermissionToDrag) {

        IDataObject data = o as IDataObject;

        if (data == null) { }
        //this line looks up the DragEntityType
        else if (data.GetDataPresent("ItemDragEntityTypeForItemWeAreDragging")) {
           returnValue = true;
        }
     }
     return returnValue;
  }

and when we drop

  private void AddItem(object o) {
     IDataObject data = o as IDataObject;

     if (data == null) { }
     else {
        MyDataObject myData = data.GetData("ItemDragEntityTypeForItemWeAreDroppingHere") as MyDataObject ;

        if (myData == null) { }
        else {
            //do something with the dropped data
        }
     }
  }

I might have missed something, but this technique lets me ask the view model if i can drag an item, and lets me ask the view model if i can drop (if the view model will accept the item) its bindable, and it seperates view/ view model nicely. If you have any questions feel free to ask.

Extended Relay Command, thanks Josh Smith...

   /// <summary>
   /// A command whose sole purpose is to 
   /// relay its ExtendedFunctionality to other
   /// objects by invoking delegates. The
   /// default return value for the CanExecute
   /// method is 'true'.
   /// </summary>
   public class ExtendedRelayCommand : ICommand {
      #region Constructors

      /// <summary>
      /// Creates a new command that can always execute.
      /// </summary>
      /// <param name="execute">The execution logic.</param>
      public ExtendedRelayCommand(Action<Object> execute)
         : this(execute, null) {
      }

      /// <summary>
      /// Creates a new command.
      /// </summary>
      /// <param name="execute">The execution logic.</param>
      /// <param name="canExecute">The execution status logic.</param>
      public ExtendedRelayCommand(Action<Object> execute, Func<Object, bool> canExecute) {
         if (execute == null)
            throw new ArgumentNullException("execute");

         _execute = execute;
         _canExecute = canExecute;
      }

      #endregion // Constructors

      #region ICommand Members

      [DebuggerStepThrough]
      public bool CanExecute(object parameter) {
         return _canExecute == null ? true : _canExecute(parameter);
      }

      public event EventHandler CanExecuteChanged {
         add {
            if (_canExecute != null)
               CommandManager.RequerySuggested += value;
         }
         remove {
            if (_canExecute != null)
               CommandManager.RequerySuggested -= value;
         }
      }

      public void Execute(object parameter) {
         _execute(parameter);
      }

      #endregion // ICommand Members

      #region Fields

      readonly Action<Object> _execute;
      readonly Func<Object, bool> _canExecute;

      #endregion // Fields
   }
Aran Mulholland