I have a usercontrol that I want to implement a drag and drop interface on, here are the vital parts of the implementation, and this works fine:
XML-file to the usercontrol to be draggable:
<UserControl
...default xmlns...
MouseLeftButtonDown="Control_MouseLeftButtonDown">
...GUI-ELEMENTS in the control...
</UserControl>
Code behind:
public partial class DragableControl : UserControl
{
private void Control_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
DragDrop.DoDragDrop(this, this, DragDropEffects.Move);
}
}
XML-file to the usercontrol which will be able to accept a drag and drop operation:
<Usercontrol
...default xmlns...>
<Grid AllowDrop="True" Drop="Grid_Drop">
... GUI elements in the grid....
</Grid>
</Usercontrol>
Code behind:
public partial class DropClass: UserControl
{
private void Grid_Drop(object sender, DragEventArgs e)
{
var control = (DragableControl)e.Data.GetData(typeof(DragableControl));
if(control != null)
{
//do something
}
}
}
To be able to create different usercontrols which have drag and drop functionality, I creates a base class, BaseDragableUserControl, which at the moment contains nothing, but inherits from usercontrol.
Code:
public class BaseDragableUserControl: UserControl
{
}
I change my code (both xaml and code):
public partial class DragableControl : UserControl
I also changes the class for receiving to this:
public partial class DropClass: UserControl
{
private void Grid_Drop(object sender, DragEventArgs e)
{
var control =(BaseDragableUserControl)e.Data.GetData(typeof(BaseDragableUserControl));
if(control != null)
{
//do something
}
}
}
But the control variable is always Null. I guess that the getdata in the DragEventsArgs does 开发者_开发百科not like inheritance. Is there a way to achieve this? To make it possible to use a base class for a drag and drop class?
Instead of passing this
when you initiate the drag/drop, create one of the standard containers for that purpose. Specifically:
DragDrop.DoDragDrop(this, new DataObject("myFormat", this), DragDropEffects.Move);
and then now you know to expect a specific kind of data:
var control =(BaseDragableUserControl)e.Data.GetData("myFormat");
精彩评论