listbox dragdrop in wpf
I am currently porting a windows forms application to wpf. There is a listbox with filenames in it. It should be possible to drag (multiple) items to the windows explorer. This was easy in w开发者_如何学编程ith the old windows form, but I can't find a way how this can be done in wpf.
This was the code I used with windows forms:
void listView1_ItemDrag(object sender, ItemDragEventArgs e)
{
string[] files = GetSelection();
if (files != null)
{
DoDragDrop(new DataObject(DataFormats.FileDrop, files), DragDropEffects.Copy );
}
}
Ok... I found a solution for my Problem, based on this tutorial:
private void List_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
// Store the mouse position
startPoint = e.GetPosition(null);
}
private void List_MouseMove(object sender, MouseEventArgs e)
{
// Get the current mouse position
Point mousePos = e.GetPosition(null);
Vector diff = startPoint - mousePos;
if (e.LeftButton == MouseButtonState.Pressed &&
Math.Abs(diff.X) > SystemParameters.MinimumHorizontalDragDistance &&
Math.Abs(diff.Y) > SystemParameters.MinimumVerticalDragDistance)
{
if (listView1.SelectedItems.Count == 0)
{
return;
}
string[] files = GetSelection();
string dataFormat = DataFormats.FileDrop;
DataObject dataObject = new DataObject(dataFormat, files);
DragDrop.DoDragDrop(listView1, dataObject, DragDropEffects.Copy);
}
}
Try checking out Bea Stollnitz' blog for a thorough implementation of drag and drop in WPF.
Bea Stollnitz - How can I drag and drop items between data bound ItemsControls?
try this code that help u to solve your problem
public partial class MainWindow : Window
{
List<string> file = new List<string>();
public MainWindow()
{
InitializeComponent();
file.Add(@"D:\file1.txt");
file.Add(@"D:\folder1");
file.Add(@"D:\folder2");
file.Add(@"D:\folder3");
lstTest.DataContext = file;
}
private Point start;
private void lstTest_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
this.start = e.GetPosition(null);
}
private void lstTest_MouseMove(object sender, MouseEventArgs e)
{
Point mpos = e.GetPosition(null);
Vector diff = this.start - mpos;
if (e.LeftButton == MouseButtonState.Pressed && Math.Abs(diff.X) > SystemParameters.MinimumHorizontalDragDistance && Math.Abs(diff.Y) > SystemParameters.MinimumVerticalDragDistance)
{
if (this.lstTest.SelectedItems.Count == 0)
{
return;
}
string[] Files = new string[file.Count] ;
for (int i = 0; i < file.Count; i++)
{
Files[i] = file[i];
}
string dataFormat = DataFormats.FileDrop;
DataObject dataObject = new DataObject(dataFormat, (lstTest.SelectedItems.Cast<string>()).ToArray<string>());
DragDrop.DoDragDrop(this, dataObject, DragDropEffects.Copy);
}
}
}
make sure you checked ( checkbox ) the multiple selection option
精彩评论