如何从DragEventArgs确定数据类型 [英] How to determine data type from DragEventArgs

查看:101
本文介绍了如何从DragEventArgs确定数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在我的应用程序中实现了拖放,但确定被拖动对象的类型有一些困难。我有一个基类指标和从它派生的几个类。拖动的对象可以是任何这些类型。下面的代码片段似乎不合适,容易出现维护问题。每次我们添加一个新的派生类,我们必须记住触摸这个代码。看来我们应该可以在这里使用继承。

  protected override void OnDragOver(DragEventArgs e)
{
base.OnDragOver(e);

e.Effect = DragDropEffects.None;

//如果拖动数据是指标类型
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) ;

//从DragEvent获取拖动的指标
指标指标=(指标)e.Data.GetData(typeof(指标))??
(指标)e.Data.GetData(typeof(IndicA))??
(指标)e.Data.GetData(typeof(IndicatorB))?
(指标)e.Data.GetData(typeof(Indicc))?
(指标)e.Data.GetData(typeof(IndicatorD));
}

谢谢。

解决方案

通过明确指定类型来存储数据,例如

  dataObject.SetData(typeof (指标),您的指标); 

这将允许您根据指标类型,而不是子类型。


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.

这篇关于如何从DragEventArgs确定数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆