I have implemented drag and drop in my application, but am having some difficulty determining the type of the object being dragged. I have a base class Indicator
and several classes derived from it. A dragged object could be of any of these types. The code snippet below seems inelegant and is prone to maintenance issues. Every time we add a new derived class, we have to remember to touch this code. It seems like we should be able to use inheritance here somehow.
protected override void OnDragOver(DragEventArgs e)
{
base.OnDragOver(e);
e.Effect = DragDropEffects.None;
// If the drag data is an "Indicator" type
if (e.Data.GetDataPresent(typeof(Indicator)) ||
e.Data.GetDataPresent(typeof(IndicatorA)) ||
e.Data.GetDataPresent(typeof(IndicatorB)) ||
e.Data.GetDataPresent(typeof(IndicatorC)) ||
e.Data.GetDataPresent(typeof(IndicatorD)))
{
e.Effect = DragDropEffects.Move;
}
}
Similarly, we have issues using GetData to actually get the dragged object:
protected override void OnDragDrop(DragEventArgs e)
{
base.OnDragDrop(e);
// Get the dragged indicator from the DragEvent
Indicator indicator = (Indicator)e.Data.GetData(typeof(Indicator)) ??
(Indicator)e.Data.GetData(typeof(IndicatorA)) ??
(Indicator)e.Data.GetData(typeof(IndicatorB)) ??
(Indicator)e.Data.GetData(typeof(IndicatorC)) ??
(Indicator)e.Data.GetData(typeof(IndicatorD));
}
Thanks.
Store your data by explicitly specifying the type, i.e.
dataObject.SetData(typeof(Indicator), yourIndicator);
This will allow you to retrieve it just based on the Indicator
type, rather than the child type.
There's the IDataObject.GetFormats
method:
Returns a list of all formats that data stored in this instance is associated with or can be converted to.
It's an array of String
:
String[] allFormats = myDataObject.GetFormats();
You could then check that list for your type, one of which should be Indicator
I would have thought.
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