Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
357 views
in Technique[技术] by (71.8m points)

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

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 specific type say SomeType and all the types that derived from it. Seems GetDataPresent doesn't support such requirement.

Any idea?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...