如何从 DragEventArgs 确定数据类型

Posted

技术标签:

【中文标题】如何从 DragEventArgs 确定数据类型【英文标题】:How to determine data type from DragEventArgs 【发布时间】:2011-03-10 04:01:33 【问题描述】:

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

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

谢谢。

【问题讨论】:

【参考方案1】:

通过明确指定类型来存储您的数据,即

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

这将允许您仅基于 Indicator 类型而不是子类型来检索它。

【讨论】:

这就像一个冠军!要完成您的解决方案:在 OnMouseDown 内部,我曾经有:DoDragDrop(indicator, DragDropEffects.Move);现在,它看起来像这样: DataObject d = new DataObject(); d.SetData(typeof(Indicator), 指标); DoDragDrop(d, DragDropEffects.Move);【参考方案2】:

IDataObject.GetFormats 方法:

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

这是一个String的数组:

String[] allFormats = myDataObject.GetFormats();

然后您可以检查您的类型的列表,其中一个应该是 Indicator 我会想到的。

【讨论】:

以上是关于如何从 DragEventArgs 确定数据类型的主要内容,如果未能解决你的问题,请参考以下文章

java中String类型怎么根据不确定的空格数将其切成数组啊

如何确定从我的 html 表单获取的输入值的数据类型,以便我可以使用它们在准备好的语句中绑定参数

在linux下怎样用fread函数从输入端读取数据,输入的数据数不确定,就是从从终端想输多少就读多少那种

在delphi 7 中各种数据类型占用字节数

如何确定线程池中线程数量

任务中如何确定spark分区数task数目core个数worker节点个数excutor数量