How to deal with GetDataPresent to let it accept all the derived types

后端 未结 2 1869
醉话见心
醉话见心 2020-12-15 10:09

I\'m using drgevent.Data.GetDataPresent to determine whether the dragged component is acceptable or not.

I\'ve got a problem which is that I want to accept a specifi

2条回答
  •  渐次进展
    2020-12-15 10:49

    Just don't use GetDataPresent(), it is boilerplate but you're free to do it your way. Actually retrieve the object and check if you're happy with its type:

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

    Where Base is the name of the base class. While the use of GetFormats() looks odd, this approach is guaranteed to work because dragging a .NET object only ever produces one format, the display name of the type of the object. Which is also the reason that GetDataPresent can't work for derived objects.

提交回复
热议问题