【问题标题】:WPF Drag and Drop - Get original source info from DragEventArgsWPF 拖放 - 从 DragEventArgs 获取原始源信息
【发布时间】:2010-12-23 12:44:14
【问题描述】:

我正在尝试使用MVVM 编写拖放功能,这将允许我将PersonModel 对象从一个ListView 拖到另一个。

这几乎可以工作,但我需要能够从 DragEventArgs 中获取源 ListView 的 ItemsSource,但我不知道该怎么做。

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

任何帮助将不胜感激。

谢谢!

【问题讨论】:

  • 在我的拖放实现中,我创建了类 DragManager(即单例)并添加了一个私有字段 draggingElement。因为一次只能拖动一个元素。

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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2019-12-12
    • 1970-01-01
    • 2022-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-11
    • 2014-09-17
    相关资源
    最近更新 更多