我正在使用drgevent.Data.GetDataPresent来确定拖动的组件是否可以接受。
我遇到了一个问题,就是我想接受一个特定的类型,说SomeType以及从中派生的所有类型。似乎GetDataPresent
不支持此类要求。
有什么想法吗?
答案 0 :(得分:19)
只是不要使用GetDataPresent(),它是样板文件,但你可以自由地按照自己的方式进行操作。实际上检索对象并检查您是否对其类型感到满意:
protected override void OnDragEnter(DragEventArgs drgevent) {
var obj = drgevent.Data.GetData(drgevent.Data.GetFormats()[0]);
if (typeof(Base).IsAssignableFrom(obj.GetType())) {
drgevent.Effect = DragDropEffects.Copy;
}
}
其中Base是基类的名称。虽然GetFormats()的使用看起来很奇怪,但这种方法可以保证工作,因为拖动.NET对象只会生成一个格式,即对象类型的显示名称。这也是GetDataPresent无法用于派生对象的原因。
答案 1 :(得分:6)
我之前回答过类似的问题:C# Drag and Drop - e.Data.GetData using a base class
您可以做的是创建一个容器类,其中包含您要拖动的数据。然后在GetDataPresent中检查容器类类型,如果它存在,那么您可以读取包含数据实际实例的内容成员。
这是一个简单的例子,如果你的基类型是DragDropBaseData,你可以创建以下DragDropInfo类。
public class DragDropInfo
{
public DragDropBaseData Value { get; private set; }
public DragDropInfo(DragDropBaseData value)
{
this.Value= value;
}
}
然后可以使用以下命令启动拖放,其中DrafDropDerivedData是从DragDropBaseData派生的类。
DoDragDrop(new DragDropInfo(new DragDropDerivedData() ), DragDropEffects.All);
您可以使用以下
访问拖动事件中的数据e.Data.GetData(typeof(DragDropInfo));
答案 2 :(得分:0)
我遇到了类似的问题。我希望它仅将 DragDrop 与接口一起使用,而这在以太网中不起作用。 所以我把我的数据放到一个对象数组中。
DoDragDrop(_dragDropSource, new[] { _dragDropSource.DataContext }, DragDropEffects.Move);
if (((object[]) e.Data.GetData(typeof(object[])))?[0] is ICatTreeViewGroup group) {
// do something with a group
}