WPF Drag and Drop - Get Original Source Information from DragEventArgs

I am trying to write a Drag and Drop function using MVVM that will allow me to drag and drop PersonModel objects from one ListView to another.

This almost works, but I need to be able to get the ItemsSource of the original ListView from DragEventArgs, which I cannot figure out how to do this.

 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!

+4
source share
1 answer

I found the answer to another question

The way to do this is to pass the original ListView to the DragDrow.DoDragDrop method, i.e.

In the method that handles PreviewMouseMove for 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); } } } 
+4
source

Source: https://habr.com/ru/post/1333187/


All Articles