变量变化触发事件 [英] Change in variable triggers an event

查看:231
本文介绍了变量变化触发事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以通过更改变量来触发事件?例如。

Is triggering an event via a change in variable possible? For example.

这将触发事件

Dim t As Integer
Dim Fire As Boolean

Private Sub Test
t = 0
Fire = True
IIf Fire, t=1, t=2
End sub

在事件处理程序中

Select Case t
    Case 0
       'Do something
    Case 1
       'Do something            
    Case 2
       'Do something
    Case 3
       'Do something
    ...   

Google调出了事件处理程序,并使用了类模块,但我无法绕开它。

Google brings up Event handlers, and using class modules but I am unable to wrap my head around it.

推荐答案

是的可能。但是,您将需要一种面向对象的方法。
首先,您需要定义一个引发您希望挂接的事件的类。其次,您将需要一个实际处理事件的类,因为您不能在常规模块中使用事件处理程序。
第三,您可以在常规模块中使用这些类。

Yes this is possible. However, you'll need an Object Oriented approach. You first need to define a class that raises the events you wish to hook into. Secondly you'll need a class that actually handles the event, since you can not use event handlers in a regular module. Thirdly, in your regular module you can then just use these classes.

这里有一个简单的示例:
创建一个名为 ClassWithEvent的类模块。放置以下代码:

Here's a simple example: Create a class module named "ClassWithEvent". Place the following code:

Public Event VariableChange(value As Integer)
Private p_int As Integer
Public Property Get value() As Integer
    value = p_int
End Property
Public Property Let value(value As Integer)
    If p_int <> value Then RaiseEvent VariableChange(value) 'Only raise on actual change.
    p_int = value
End Property

接下来,创建可以处理的类此类引发的事件。
将此类模块命名为 ClassHandlesEvent。在其中放置以下代码:

Next, create the class that can handle the events raised by this class. Name this Class Module "ClassHandlesEvent". Place the following code in it:

Private WithEvents SomeVar As ClassWithEvent
Private Sub SomeVar_VariableChange(value As Integer) 'This is the event handler.
    Select Case value
        Case 1:
            MsgBox "here, 1!"
        Case 2:
            MsgBox "here, 2!"
        Case Default:
            'Do Nothing
    End Select
End Sub
Public Property Get EventVariable() As ClassWithEvent
    Set EventVariable = SomeVar
End Property
Public Property Let EventVariable(value As ClassWithEvent)
    Set SomeVar = value
End Property

接下来,在常规模块中,实例化ClassWithEvent并将其作为属性传递给处理它们的类。

Next, in a regular module, instantiate your ClassWithEvent and pass this one as a property to the class that handles them.

Sub test()
    Dim var As ClassHandlesEvent
    Dim tst As ClassWithEvent

    Set var = New ClassHandlesEvent
    Set tst = New ClassWithEvent
    var.EventVariable = tst

    tst.value = 2 'A messagebox saying "Here, 2!" will pop-up
End Sub

这篇关于变量变化触发事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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