如何处理GetDataPresent以让它接受所有派生类型
我使用 drgevent.Data.GetDataPresent 来确定拖动的组件是否是否可以接受。
我有一个问题,我想接受特定类型(例如 SomeType)以及从它派生的所有类型。似乎GetDataPresent
不支持这样的要求。
有什么想法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
只是不要使用 GetDataPresent(),它是样板文件,但您可以自由地按照自己的方式进行操作。实际检索对象并检查您是否对其类型感到满意:
其中 Base 是基类的名称。虽然 GetFormats() 的使用看起来很奇怪,但这种方法保证有效,因为拖动 .NET 对象只会产生一种格式,即对象类型的显示名称。这也是 GetDataPresent 不能用于派生对象的原因。
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:
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.
我之前回答过类似的问题: C# 拖放 - 使用基类的 e.Data.GetData
您可以做的是创建一个容器类来保存您正在拖动的数据。然后在 GetDataPresent 中检查容器类类型,如果存在,则可以读取包含数据实际实例的内容成员。
这是一个简单的示例,如果您的基类型是 DragDropBaseData,则可以创建以下 DragDropInfo 类。
然后可以使用以下代码启动拖放,其中 DrafDropDerivedData 是从 DragDropBaseData 派生的类。
您可以使用以下命令访问拖动事件中的数据
I have answered a similar question previously: C# Drag and Drop - e.Data.GetData using a base class
What you can do is create a container class which holds the data that you are dragging. And then in the GetDataPresent you check for the container class type and if it is present then you can read the content member which contains the actual instance of your data.
Here is an quick example, if your base type is DragDropBaseData, you can create the following DragDropInfo class.
And then the drag drop can be initiated with the following, where DrafDropDerivedData is a class derived from DragDropBaseData.
And you can access the data in the drag events using the following
我有类似的问题。我希望它仅在接口中使用 DragDrop,这不起作用。
所以我将数据放入对象数组中。
I had a similar problem. I want it to use DragDrop only with interfaces, which doesn't work ether.
So I put my data in to an array of object.