代码之家  ›  专栏  ›  技术社区  ›  Dustin Brooks

使用基类拖放-e.data.getdata

  •  7
  • Dustin Brooks  · 技术社区  · 16 年前

    我正在使用C和WinForms 3.5

    我有一个用户控件列表,所有这些控件都是从一个基类派生的。这些控件可以添加到不同的面板中,我正在尝试实现拖放功能,我遇到的问题是DragDrop事件。

    对于DragEventArgs e.Data.GetData(typeof(baseClass)) 不起作用。它想要:

    e.Data.GetData(typeof(derivedClass1))
    e.Data.GetData(typeof(derivedClass2))
    etc...
    

    有什么方法可以解决这个问题,或者更好的设计方法吗?

    2 回复  |  直到 16 年前
        1
  •  17
  •   Chris Taylor    16 年前

    您可以将数据包装在一个公共类中。例如,假设您的基类称为DragDropBaseControl

    public class DragDropInfo
    {
      public DragDropBaseControl Control { get; private set; }
    
      public DragDropInfo(DragDropBaseControl control)
      {
        this.Control = control;
      }
    }
    

    然后,可以用基类中的以下内容启动拖放

    DoDragDrop(new DragDropInfo(this), DragDropEffects.All);
    

    您可以使用以下方法访问拖动事件中的数据

    e.Data.GetData(typeof(DragDropInfo));
    

    我正确理解你的要求了吗?

        2
  •  0
  •   Abdulhameed    8 年前

    为了动态获取拖动对象,甚至不知道其类型或其基类型,我在 DragDrop 事件:

    baseClass myObject = (baseClass)e.Data.GetData(e.Data.GetFormats()[0]);
    

    作为 e.Data.GetFormats()[0] 将始终保持拖动对象类型的字符串表示形式。

    注意,我假设有一个对象被拖动,但对于多个拖动的对象,这个想法是相同的。