VB.NET-如何将大量事件添加到单个句柄? [英] VB.NET - How to add a large amount of events to a single handle?

查看:117
本文介绍了VB.NET-如何将大量事件添加到单个句柄?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我正在开发一个包含几个TextBoxes,CheckBoxes,ComboBoxes等的程序,我发现使一个函数处理多个事件非常简单,您只需用逗号和代码分隔事件识别单个事件.

Recently I've been working on a program that has a few TextBoxes, CheckBoxes, ComboBoxes, etc., and I found that making one function handle multiple events is pretty simple, you just separate the events with a comma and the code recognizes the inidvidual events.

Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click, Button2.Click
    MsgBox("Hello World!")
End Sub

但是,当您开始具有要由同一功能处理的大量事件时,它会变得有些混乱.

However, when you start to have a large number of events that you want handled by the same function, it gets a bit messy.

Private Sub Checks_CheckedChanged(sender As Object, e As EventArgs) Handles chkInput1.CheckedChanged, chkInput2.CheckedChanged, chkInput3.CheckedChanged, chkInput4.CheckedChanged, checkInput5.CheckedChanged, chkOutput.CheckedChanged
    MsgBox("Checks Changed!")
End Sub

您可以使用换行字符_使其看起来更好一些.

You can use the line continuation character _ to make it look a little better.

Private Sub Checks_CheckedChanged(sender As Object, e As EventArgs) Handles _
chkInput1.CheckedChanged, chkInput2.CheckedChanged, chkInput3.CheckedChanged, _
chkInput4.CheckedChanged, checkInput5.CheckedChanged, chkOutput.CheckedChanged
    MsgBox("Checks Changed!")
End Sub

但是您仍然会遇到讨厌的文本块.有没有更简洁的方法?我想到的是,将一系列对象事件作为参数确实很不错,但我认为这是不可能的.

But you still end up with a nasty block of text. Is there a more clean/concise way of doing this? What I have in mind is that it would be really nice to give an array of object events as an argument but I don't think that's possible.

推荐答案

您可以使用

AddHandler ObjectName.EventName, AddressOf EventHandlerName

语法

编写一个Sub,它接受一个对象数组并在其上循环以为每个事件添加处理程序,就足够简单了.

It's simple enough to write a Sub that takes an array of object and loops over them to add the handler for each event.

对于复选框:

Public Sub AddHandlerSub(PassedArray As CheckBox())
    For Each item As CheckBox in PassedArray
        AddHandler Item.CheckedChanged, AddressOf EventHandlerName
    next
End Sub

这篇关于VB.NET-如何将大量事件添加到单个句柄?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆