Nas*_*rEd 8 drag-and-drop winforms
我已经在我的应用程序中实现了拖放操作,但是在确定被拖动对象的类型时遇到了一些困难.我有一个基类Indicator和几个派生自它的类.拖动的对象可以是任何这些类型.下面的代码片段似乎不够优雅,容易出现维护问题.每次我们添加一个新的派生类时,我们都要记得触摸这个代码.看起来我们应该能够以某种方式使用继承.
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;
}
}
Run Code Online (Sandbox Code Playgroud)
同样,我们使用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));
}
Run Code Online (Sandbox Code Playgroud)
谢谢.
通过明确指定类型来存储数据,即
dataObject.SetData(typeof(Indicator), yourIndicator);
Run Code Online (Sandbox Code Playgroud)
这将允许您仅根据Indicator类型而不是子类型来检索它.
| 归档时间: |
|
| 查看次数: |
6445 次 |
| 最近记录: |