WPF中LISTITEM的拖拽
此方法较容易实现list中项的拖拽,不过其缺陷是无法将选中的ITEM取出来,SELECTED事件被MOUSELEFTBUTTONDOWN吃掉了。
不罗嗦了,以下是DEMO的源码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using System.Collections;
namespace DragTest
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
ObservableCollection<string> obv = new ObservableCollection<string>();
public MainWindow()
{
InitializeComponent();
foreach (TimeZoneInfo tzi in TimeZoneInfo.GetSystemTimeZones())
{
lst1.Items.Add(tzi.ToString());
}
}
ListView dragSource = null;
private void lst1_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
ListView parent = (ListView)sender;
dragSource = parent;
object data = GetDataFromListBox(dragSource, e.GetPosition(parent));
if (data != null)
{
DragDrop.DoDragDrop(parent, data, DragDropEffects.Copy);
}
}
private static object GetDataFromListBox(ListBox source, Point point)
{
UIElement element = source.InputHitTest(point) as UIElement;
if (element != null)
{
object data = DependencyProperty.UnsetValue;
while (data == DependencyProperty.UnsetValue)
{
data = source.ItemContainerGenerator.ItemFromContainer(element);
if (data == DependencyProperty.UnsetValue)
{
element = VisualTreeHelper.GetParent(element) as UIElement;
}
if (element == source)
{
return null;
}
}
if (data != DependencyProperty.UnsetValue)
{
return data;
}
}
return null;
}
//listbox1 to listbox2
private void lst2_Drop(object sender, DragEventArgs e)
{
ListView parent = (ListView)sender;
if (parent.Name == lst2.Name)
{
object data = e.Data.GetData(typeof(string));
((IList)dragSource.Items).Remove(data);
if (!parent.Items.Contains(data))
{
parent.Items.Add(data);
}
}
}
//listbox2 to listbox1
private void lst1_Drop(object sender, DragEventArgs e)
{
ListView parent = (ListView)sender;
if (parent.Name == lst1.Name)
{
object data = e.Data.GetData(typeof(string));
((IList)dragSource.Items).Remove(data);
if (!parent.Items.Contains(data))
{
parent.Items.Add(data);
}
}
}
private void lst2_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
ListView parent = (ListView)sender;
dragSource = parent;
object data = GetDataFromListBox(dragSource, e.GetPosition(parent));
if (data != null)
{
DragDrop.DoDragDrop(parent, data, DragDropEffects.Move);
}
}
}
}