处理各种控件的事件

发布于 2024-11-02 06:13:21 字数 304 浏览 0 评论 0原文

我想使用以下片段。

    For Each x As Control In Me.Controls
        If TypeOf x Is CustomControl Then
            SomeAction( x.CustomEventofCustomControl)
        End If
    Next

这里的问题是,并非所有控件都有 CustomEventofCustomControl 事件,因此编译器会尖叫。我该如何解决这个问题。

ps:有什么更好的标题的想法吗?

I want to use the following snippit.

    For Each x As Control In Me.Controls
        If TypeOf x Is CustomControl Then
            SomeAction( x.CustomEventofCustomControl)
        End If
    Next

The problem here is that not all controls have event CustomEventofCustomControl, so the complier shrieks. How do I get around this.

ps: Any ideas for a better title?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

以可爱出名 2024-11-09 06:13:21

一个好主意是使用一些标记接口,例如 IHasWhateverEvent(告诉我是哪个,当然,我会编写一个更好的名称!)。该接口没有成员,因为它是一个标记接口。

您可以使任何具有该事件的自定义控件实现此空白接口,然后您可以这样做:

For Each x As Control In Me.Controls
        If x Is IHasWhateverEvent Then
            SomeAction(((IHasWhateverEvent)x).CustomEventofCustomControl)
        End If
Next

或者如果可以的话,只需在接口中添加一个事件,这样当您将某些控件强制转换为 IHasWhateverEvent 时,您就可以访问该事件本身。

A good idea would be use some marker interface like IHasWhateverEvent (tell me which one and I'll compose a better name, of course!). That interface has no members, since it's a marker one.

You make any of your custom controls having that event implement this blank interface, then you do that:

For Each x As Control In Me.Controls
        If x Is IHasWhateverEvent Then
            SomeAction(((IHasWhateverEvent)x).CustomEventofCustomControl)
        End If
Next

Or if you can, just add an event in your interface so when you cast some control to IHasWhateverEvent, you'll have access to the event itself.

国际总奸 2024-11-09 06:13:21

什么为我解决了问题:

 For Each x As Control In Me.Controls
        If TypeOf x Is CustomControl Then
            SomeAction( CType(x, CustomControl).CustomEventofCustomControl)
        End If
    Next

What solved the problem for me:

 For Each x As Control In Me.Controls
        If TypeOf x Is CustomControl Then
            SomeAction( CType(x, CustomControl).CustomEventofCustomControl)
        End If
    Next
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文