woensdag 20 januari 2010

Drag & Drop

Basic drag & drop is pretty easy to accomplish in WPF. For starters you should add a MouseMove handler to the object you want to drag around. When you detect the left mouse button is pressed you initiate the drag and pass the source and data to the drag & drop method.

     private void border_PreviewMouseMove(object sender, MouseEventArgs e)
{
Border border = (Border)sender;
if (e.LeftButton == MouseButtonState.Pressed)
{
DragDropEffects dropEffect = DragDrop.DoDragDrop(border, border.Child, DragDropEffects.Move);
}
}

Any object you want to drop another object inside needs to have the 'AllowDrop' property set to true. When that's done you add a handler to handle the drop event. Inside you should check the type of the data being dropped and if it is what you expect then you can deal with it accordingly. In this case the Border object had an Image object set as its child.

     private void grdPdf_Drop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(Image)))
{
Image image = (Image)e.Data.GetData(typeof(Image));
}
}

Geen opmerkingen:

Een reactie posten