WPF Drag and Drop - Get original source info from DragEventArgs

扶醉桌前 提交于 2019-12-19 20:47:31

问题


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!


回答1:


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);
        }
    }
}


来源:https://stackoverflow.com/questions/4518856/wpf-drag-and-drop-get-original-source-info-from-drageventargs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!