Recently I was tasked with making a utility app to manage records in a database. Since there were no requirements for this other than it had to actually do the updates I decided to use WPF and even try to use MVVM since I thought a small project would get me more familiar with both. The overall app wasn’t that hard, basically the first window opened a second window to perform searches and allowed the searched items to be added to the main window where they would be edited. Basically I was taking items from one GridView to another. I had made buttons to do the moving that were linked to Commands that actually moved the data.
Once I was done I was challenged to allow dragging and dropping from the search grid to the main grid. I was told it was pretty trivial but having only made simple test apps I was skeptical. Turns out it wasn’t nearly as bad as I thought. All I had to do for the search grid was handle the PreviewMouseLeftButtonDown event and call DragDrop.DoDragDrop and pass in the appropriate values. Then in the main grid I set the AllowDrop property to true and handled the Drop event. One thing to note is that I had to make sure the item I was selecting in the search grid was not already selected as it was causing some weird behavior with selecting the items and dragging them, I am not sure why.
Here is the code for the search grid, I got that cast to the framework element from the quick watch window:
- private void ListView_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
- {
- MenuItemLite item = (MenuItemLite)((System.Windows.FrameworkElement)(e.OriginalSource)).DataContext;
- if (item != null && item.IsSelected)
- DragDrop.DoDragDrop(lstSearch, this.DataContext, DragDropEffects.Copy);
- }
Here is the code in the drop event for the main grid:
- private void ListView_Drop(object sender, DragEventArgs e)
- {
- MainViewModel vm = (MainViewModel)this.DataContext;
- vm.Add.Execute(this);
- }
Since I used MVVM I just got a reference to the data context of the Views, cast them to the appropriate type and called the appropriate command to handle taking items from one grid to another. I struggled with some things in MVVM but it made doing drag and drop very easy for me. Hope this helps