WPF拖放 - 从DragEventArgs获取原始源信息

时间:2010-12-23 12:44:14

标签: c# wpf mvvm drag-and-drop

我正在尝试使用MVVM编写拖放功能,这样我就可以将PersonModel个对象从一个ListView拖到另一个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); } }

这几乎可以工作但我需要能够从DragEventArgs获取源ListView的ItemsSource,而我无法弄清楚该怎么做。

{{1}}

非常感谢任何帮助。

谢谢!

1 个答案:

答案 0 :(得分:4)

我在another question

中找到了答案

这样做的方法是将源ListView传递给DragDrow.DoDragDrop方法,即。

在处理ListView的PreviewMouseMove的方法中 -

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

然后在OnHandleDrop方法中将代码更改为

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