65.9K
CodeProject 正在变化。 阅读更多。
Home

在拖放操作期间修改 DataObject

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.80/5 (3投票s)

2010年12月15日

CPOL

2分钟阅读

viewsIcon

36293

downloadIcon

737

一个关于如何在拖放事件中处理和修改数据对象的演示

引言

这个简单的拖放演示展示了如何在拖放操作期间修改 DataObject。 如果您希望在最终拖放到目标位置之前提供用户交互,这将非常有用。 一个很好的用例是创建一个工具箱,用于将项目添加到目标位置(窗体、列表框、网格等),您希望在拖放它们之前自定义(赋予名称、附加配置等)。

modify_drag_and_drop_data/DragDrop001.png

背景

此示例使用 .NET Framework 中的标准拖放 API,以及基本函数和事件,例如

  • DoDragDrop (方法)
  • OnDragEnter (事件)
  • OnDragDrop

概念 / 描述

该演示的概念是拥有一个可以将项目拖放到标准 ListBox 的工具箱。 该工具箱由一个带有三个 LabelPanel 组成(项目 A、项目 B 和项目 C),这些标签可以通过拖放拖到 ListBox 中。

ListBox 仅接受类型为 String 且内容为“Item A”或“Item C”的 DataObject。 在项目被拖放到 ListBox 之前,并且仅当激活了“时间戳确认?”选项时,用户必须响应以表示他是否希望将时间戳附加到他正在附加到 ListBoxstring 中。

modify_drag_and_drop_data/DragDrop002.png

代码

因此,第一步是在开始拖放操作时从 Label 创建 DataObject

private void ItemALabel_MouseMove(object sender, MouseEventArgs e) 
{  
   if (e.Button == MouseButtons.Left)  
   {  
      ItemALabel.DoDragDrop(ItemALabel.Text, DragDropEffects.All);  
   }  
}  
  
private void ItemBLabel_MouseMove(object sender, MouseEventArgs e)  
{  
   if (e.Button == MouseButtons.Left)  
   {  
      ItemBLabel.DoDragDrop(ItemBLabel.Text, DragDropEffects.All);  
   }  
}  
  
private void ItemCLabel_MouseMove(object sender, MouseEventArgs e)  
{  
   if (e.Button == MouseButtons.Left)  
   {  
      ItemCLabel.DoDragDrop(ItemCLabel.Text, DragDropEffects.All);  
   }  
}

ListBox 必须决定是否接受拖放操作。 仅接受类型为 String 且内容为“Item A”或“Item C”的 DataObject

private void ListBoxControl_DragEnter(object sender, DragEventArgs e) 
{ 
   if (e.Data.GetFormats()[0] == "System.String") 
   { 
      String dropString = (String)e.Data.GetData("System.String"); 
 
      if ((dropString == "Item A") || (dropString == "Item C")) 
      { 
         e.Effect = DragDropEffects.Copy; 
      } 
      else 
      { 
         e.Effect = DragDropEffects.None; 
      } 
   } 
   else 
   { 
      e.Effect = DragDropEffects.None; 
   } 
}

最后,在 Drop 事件上,您可以处理 DataObject 的修改

private void MainListView_DragDrop(object sender, DragEventArgs e) 
{ 
   if (TimestampCheckBox.Checked) 
   { 
      if (MessageBox.Show("Do you want to add a timestamp?", 
      "Confirmation", MessageBoxButtons.YesNoCancel) == DialogResult.Yes) 
      { 
         if (e.Data.GetFormats()[0] == "System.String") 
         { 
            String timestampedString = (String)e.Data.GetData("System.String"); 
            timestampedString = String.Format("{0} ({1})", 
            timestampedString, DateTime.Now); 
            e.Data.SetData(timestampedString); 
         } 
      } 
   } 
}

结论

如您所见,使用 .NET Framework 中的拖放 API,您具有很大的灵活性,可以处理许多不同的场景。

历史

  • 2010 年 12 月 15 日:初始修订
  • 2010 年 12 月 22 日:更新源代码以删除第三方组件
© . All rights reserved.