Hey guys, this morning (yeah, beginning 7.00) I tried to implement what seemed to be quite an easy task: Dragging files out of my app onto the desktop or into an open explorer Window.
It’s not quite easy. So let’s start this small tutorial. First (of course) you create an ListView – let’s call it “FileView”.
<ListView x:Name="FileView"
PreviewMouseLeftButtonDown="FileView_PreviewMouseLeftButtonDown"
MouseMove="FileView_MouseMove">
<ListView.View>
<GridView>
<!-- Put in here whatever you need -->
<GridViewColumn Header="Name" CellTemplate="{StaticResource file}" />
</GridView>
</ListView.View>
</ListView>
Now to the code behind the xaml. You might have noticed that I added two events to the ListView. The PreviewMouseLeftButtonDown (the dragging starts) and the MouseMove (the dragging is happening).
private Point start;
private void FileView_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
this.start = e.GetPosition(null);
}
private void FileView_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.FileView.SelectedItems.Count == 0)
{
return;
}
// right about here you get the file urls of the selected items.
// should be quite easy, if not, ask.
//string[] files = ...;
string dataFormat = DataFormats.FileDrop;
DataObject dataObject = new DataObject(dataFormat, files);
DragDrop.DoDragDrop(this.FileView, dataObject, DragDropEffects.Copy);
}
}
Now that’s that, thanks for reading.