【问题标题】:Dragging and Dropping in WPFWPF中的拖放
【发布时间】:2012-10-09 09:48:51
【问题描述】:

我的 WPF 应用程序中有 TreeViewCanvas。我正在尝试实现用户可以拖动 TreeViewItem 的功能,并且当用户放在画布上时应该调用一个方法,将 TreeViewItem 标头作为参数传递给该方法。

这是我到目前为止所做的:

private void TreeViewItem_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
     if (e.Source.GetType().Name.Equals("TreeViewItem"))
     {
         TreeViewItem item = (TreeViewItem)e.Source;

         if (item != null)
         {
              DataObject dataObject = new DataObject();
              dataObject.SetData(DataFormats.StringFormat, item.Header.ToString());
              DragDrop.DoDragDrop(item, dataObject, DragDropEffects.Copy);
         }
     }
 }

当我拖放到画布上时,什么也没有发生。因此,我不确定下一步应该做什么。我觉得这真的很小,但我不知所措。如何调用该方法并检测到标头已被丢弃?

有什么想法吗?

【问题讨论】:

  • 您的 AllowDrop 属性是否设置为 true?
  • 是的,刚刚编辑了问题:)
  • 你能发布一些代码来显示你的 Canvas 和 TreeView 的标记和代码隐藏吗?您应该有一些拖放事件处理程序。那些被抚养长大的?
  • 查看这个post的答案你可能没有正确地引发事件

标签: c# .net wpf events drag-and-drop


【解决方案1】:

您需要将目标元素上的AllowDrop 设置为true,然后处理目标元素上的DragOverDrop 事件。

例子:

    private void myElement_DragOver(object sender, DragEventArgs e)
    {
        if (!e.Data.GetDataPresent(typeof(MyDataType)))
        {
            e.Effects = DragDropEffects.None;
            e.Handled = true;
        }
    }

    private void myElement_Drop(object sender, DragEventArgs e)
    {
        if (e.Data.GetDataPresent(typeof(MyDataType)))
        {
            // do whatever you want do with the dropped element
            MyDataType droppedThingie = e.Data.GetData(typeof(MyDataType)) as MyDataType;
        }
    }

【讨论】:

  • AllowDrop 实际上设置为 true,所以这不是问题。您能否详细说明 DragOver 和 Drop 事件部分?这些应该是画布的事件吗?画布事件如何知道 drop 应该传输 TreeViewItem 的标题?
  • @DotNET:我已经编辑了我的答案,以添加 DragOver 和 Drop 事件处理程序的外观。
  • 谢谢,这应该可以帮助我解决我的问题 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-10
  • 1970-01-01
  • 2012-07-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多