2010-06-30 50 views
8

我已经在我的应用程序中实现了拖放功能,但在确定被拖动的对象的类型时遇到了一些困难。我有一个基类Indicator和从它派生的几个类。拖动的对象可以是这些类型中的任何一种。下面的代码片段看起来不够优雅,容易出现维护问题。每次我们添加一个新的派生类时,我们都必须记住触摸这个代码。似乎我们应该能够以某种方式在这里使用继承。如何从DragEventArgs中确定数据类型

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; 
    } 
    } 

同样,我们使用的GetData问题真正得到拖动的对象:

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)); 
} 

感谢。

回答

8

商店通过明确指定类型的数据,即

dataObject.SetData(typeof(Indicator), yourIndicator); 

这将允许你刚才基础上,Indicator类型进行检索,而不是子类型。

+0

这就像一个冠军! 要完成您的解决方案: 在OnMouseDown里面,我曾经有: DoDragDrop(indicator,DragDropEffects.Move); 现在,它看起来像这样: DataObject d = new DataObject(); d。设置数据(typeof(Indicator),indicator); 012DDDDDrop(d,DragDropEffects.Move); – NascarEd 2010-06-30 14:48:43

2

还有的IDataObject.GetFormats方法:

返回的存储在该实例中的数据与相关联的或可以转化为所有格式的列表。

它的String数组:

String[] allFormats = myDataObject.GetFormats(); 

然后,您可以检查清单你的类型,其中之一应该是Indicator我还以为。