WPF Drag and Drop - Get original source info from DragEventArgs
I am trying write Drag and Drop functionality using MVVM
which will allow me to drag PersonModel
objects from one ListView
to another.
This is almost working but I need to be able to get 开发者_开发技巧the ItemsSource of the source ListView from the DragEventArgs which I cant figure out how to do.
private void OnHandleDrop(DragEventArgs e)
{
if (e.Data != null && e.Data.GetDataPresent("myFormat"))
{
var person = e.Data.GetData("myFormat") as PersonModel;
//Gets the ItemsSource of the source ListView
..
//Gets the ItemsSource of the target ListView and Adds the person to it
((ObservableCollection<PersonModel>)(((ListView)e.Source).ItemsSource)).Add(person);
}
}
Any help would be greatly appreciated.
Thanks!
I found the answer in another question
The way to do it is to pass the source ListView into the DragDrow.DoDragDrop method ie.
In the method which handles the PreviewMouseMove for the ListView do-
private static void List_MouseMove(MouseEventArgs e)
{
if (e.LeftButton == MouseButtonState.Pressed)
{
if (e.Source != null)
{
DragDrop.DoDragDrop((ListView)e.Source, (ListView)e.Source, DragDropEffects.Move);
}
}
}
and then in the OnHandleDrop method change the code to
private static void OnHandleDrop(DragEventArgs e)
{
if (e.Data != null && e.Data.GetDataPresent("System.Windows.Controls.ListView"))
{
//var person = e.Data.GetData("myFormat") as PersonModel;
//Gets the ItemsSource of the source ListView and removes the person
var source = e.Data.GetData("System.Windows.Controls.ListView") as ListView;
if (source != null)
{
var person = source.SelectedItem as PersonModel;
((ObservableCollection<PersonModel>)source.ItemsSource).Remove(person);
//Gets the ItemsSource of the target ListView
((ObservableCollection<PersonModel>)(((ListView)e.Source).ItemsSource)).Add(person);
}
}
}
精彩评论