WinForm 拖拽(Drag and Drop)
WinForm 拖拽(Drag and Drop)
需求
winForm开发,将一个ListView
中的项ListViewItem
拖入到另一个ListView
控件中。自己对WinForm 开发较少,折腾了一天才整出来。总结一下,为自己增加点WinForm开发经验。
Code
- 新建
1ListBoxDrgDropListBox
Form,托人两个ListView
分别命名为:'ListDragSource','ListDragTarget' - 初始化ListDragSource中的数据
private void InitListDragSource()
{
this.ListDragSource.Items.AddRange(new ListViewItem[] {
new ListViewItem("one"),
new ListViewItem("two"),
new ListViewItem("three"),
new ListViewItem("four"),
new ListViewItem("five"),
new ListViewItem("six")
});
}
- 相关事件定义
/// <summary>
/// 拖拽ListView中的Item时触发事件
/// </summary>
/// <param name="sender">ListView</param>
/// <param name="e">参数</param>
private void ListDragSource_ItemDrag(object sender, ItemDragEventArgs e)
{
ListView lstView = sender as ListView;
if (lstView != null)
{
lstView.DoDragDrop(lstView.SelectedItems, DragDropEffects.Move);
}
}
/// <summary>
/// 当ListView中的项(Item)托离ListView时触发
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ListDragTarget_DragLeave(object sender, EventArgs e)
{
ListView lstView = sender as ListView;
if (lstView != null)
{
foreach (ListViewItem item in lstView.SelectedItems)
{
lstView.Items.Remove(item);
}
}
}
/// <summary>
/// 拖拽完成时出发
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ListDragTarget_DragDrop(object sender, DragEventArgs e)
{
ListView lstView = sender as ListView;
System.Windows.Forms.ListView.SelectedListViewItemCollection items = (System.Windows.Forms.ListView.SelectedListViewItemCollection)e.Data.GetData(typeof(System.Windows.Forms.ListView.SelectedListViewItemCollection));
if (items != null && items.Count > 0)
{
foreach (ListViewItem item in items)
{
ListViewItem itemTemp = (ListViewItem)item.Clone();
itemTemp.Name = item.Text;
if (!lstView.Items.ContainsKey(itemTemp.Name))
{
lstView.Items.Add(itemTemp);
}
}
}
}
/// <summary>
/// 当拖入ListView时除非
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ListDragTarget_DragEnter(object sender, System.Windows.Forms.DragEventArgs e)
{
e.Effect = DragDropEffects.Move;
}
ListView
拖动属性设置和事件绑定
private void ListBoxDrgDropListBox_Load(object sender, EventArgs e)
{
InitListDragSource();
//设置控件支持拖动
this.ListDragTarget.AllowDrop = true;
this.ListDragSource.AllowDrop = true;
this.ListDragSource.ItemDrag += new ItemDragEventHandler(ListDragSource_ItemDrag);
this.ListDragTarget.ItemDrag += new ItemDragEventHandler(ListDragSource_ItemDrag);
this.ListDragTarget.DragLeave += new EventHandler(ListDragTarget_DragLeave);
this.ListDragTarget.DragEnter += new DragEventHandler(ListDragTarget_DragEnter);
this.ListDragTarget.DragDrop += new DragEventHandler(ListDragTarget_DragDrop);
}
注意
- 设置
ListView
控件支持拖动 - 拖动事件
ItemDrag
(指ListView
控件中项事件)首先触发,必须定义实现此事件,否则后面事件不触发 - 防止重复数据拖入
lstView.Items.ContainsKey(itemTemp.Name)
,其中Key即为ListViewItem
实例的Name