I'm working on this wpf application where you can click on a StackPanel in a TreeView list and drag it onto another area of the window (in this case a map).
When I'm creating the StackPanel, I store the necessary data in the Tag attribute:
private StackPanel makeStackPanel(messageIconType itemType,
string filePath, CustomClass message)
{
StackPanel stack = new StackPanel();
stack.Orientation = Orientation.Horizontal;
stack.Tag = new List<Object>{message, itemType};
stack.MouseDown += new MouseButtonEventHandler(stack_MouseDown);
return stack;
}
When I click on the StackPanel, the event is fired for MouseDown. I make a DataObject so that I can pass the data to the method that catches the "DragDrop" event firing.
private void stack_MouseDown(object sender, System.Windows.Input.MouseEventArgs e)
{
StackPanel sp = (StackPanel)sender;
DataObject dataObj = new DataObject();
dataObj.SetData(typeof(List<Object>), (List<Object>)sp.Tag);
DragDrop.DoDragDrop(sp, dataObj, DragDropEffects.Copy);
}
When we get to the DragDrop method, e.Data.GetData(typeof(List)) returns null.
1 private void Map_DragDrop(object sender, System.Windows.Forms.DragEventArgs e)
2 {
3 string[] data = e.Data.GetFormats();
4 int i=0;
5 if(e.Data.GetDataPresent(data[0]))
6 {
7 i++;
8 }
9 if (e.Data.GetDataPresent(typeof(List<Object>)))
10 {
11 i++;
12 }
13 List<Object> obj = (List<Object>)e.Data.GetData(typeof(List<Object>));
14 }
The lines before that are sanity checks. e.Data.GetFormats() returns a string saying that the format is a List. Lines 5 and 9 both evaluate to true, so there is Data of type List. When I'm in debugging, if I dig deep enough in the DragEventArgs e, I can find my data. It's just that in line 14, it always returns null and I can't find any other way of getting that data.
Instead of passing an instance of Object List, create a class with Property Data of type object. Create an instance of the class and set the Data Property with the object you want to Drag In the Map_DragDrop event call GetData(), passing the typeof(MyDraggedData) as argument and cast back to the original object
lookup DataFormats class and IDataObject implementation
public class MyDraggedData
{
public object Data { get; set; }
}
private void stack_MouseDown(object sender, System.Windows.Input.MouseEventArgs e)
{
StackPanel sp = (StackPanel)sender;
MyDraggedData data = new MyDraggedData();
data.Data = sp.Tag;
DragDrop.DoDragDrop(sp, data, DragDropEffects.Copy);
}
private void Map_DragDrop(object sender, System.Windows.Forms.DragEventArgs e)
{
MyDraggedData data = (MyDraggedData)e.Data.GetData(typeof(MyDraggedData));
List<Object> obj = (List<Object>)data.Data;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With