views:

543

answers:

1

I've got two ListBox's with objects as an ItemsSource populating them. Right now, I'm using a DragDropHelper to let me drag an object from one ListBox to the 2nd ListBox. I run custom code to change an attribute on the Object and update my two ListBox collections of objects.

However, now I want to be able to drop one of these objects onto another control in the window. But, I dont want to necessarily "DROP" the object. I just want the external control to realize (by raising an event) that it just got dropped onto by an object with an ID.

To recap, I've got 2 listboxes. one listbox is Favorites, the other is NonFavorites. I can happily drag/drop between the two listboxes and everything works. now i want to drag a favorite/nonfavorite away from the listboxes and drop it onto another control. I want that control to simply say "HEY! I just got a favorite/nonfavorite object dropped on me".

any ideas?

A: 

I did something similar to this last year (.NET .3.5).

If I remember correctly when you "Drop" an object which has been selected and dragged (via the adorner layer) you are in essence holding a reference to the selected object. When that object is "Dropped" the "InstanceDroppedOnUserControlFoo_Handler(... args)" event handler has a untyped reference to the object that has been dropped.

From this you can cast (if the type is known) and access the Id field to your hearts content.

The question now is, does the drop target user control share the same ViewModel in it's DataContext as that of the Drag Source? As in most cases where this is not the case you will not get a reference in the event args, you will get null.

If this is the case you will need to explore these options for inter ViewModel communication:

Use a MVVM message passing framework (MVVM Light Framework see Messenger component) or Pub Sub composite events via the WPF Prism - EventAggregator:

Then follow this process (or something more tailored to your needs):

  • When an item has been selected and is being Dragged, hold its reference in a property of your Drag Source's ViewModel.
  • When the item is dropped, publish a message saying "I want the reference to the selected item which was being dragged".
  • The Drag Source can publish a message in response with the reference to the object which was dragged which will be received by the requesting ViewModel.

Obviously you can tailor the reference holding at this point to your needs. I will leave you with one last suggestion, it may be worth while considering the use of a controller class which manages this kind of operation. I have seen a controller being used by the Microsoft's Patterns & Practises in coordination with MVVM in the WPF CAG (PRISM) samples, so it is not unheard of.

StevenH