开发者

How Do I Get an Object to Listen For its Property's Event?

开发者 https://www.devze.com 2022-12-14 04:41 出处:网络
I have an object of type SomeObject, with an event StatusChanged. I have a property in SomeObject of type Status also with an event StatusChanged.

I have an object of type SomeObject, with an event StatusChanged.

I have a property in SomeObject of type Status also with an event StatusChanged.

Within a private function in SomeObject, I would like to run some logic (including firing the StatusChanged event) in the event that Status has fired its StatusChanged event. I have been away from events for a while so it's a bit cloudy to me. How do I do this?

I'm writing in ASP.NET/VB.NET

Thanks :)

EDIT Ok, in the event that I can't do the above, how would I get the outer object (SomeObject) to fire its StatusChanged event when the inner 开发者_StackOverflow社区object (Status) fires its StatusChanged event?


Events don't work that way. You can't perform logic based on whether an event has been fired. You can only write logic that takes place when an event is fired.


Ok, here's an attempt. It's been a while since I've done this in VB.NET, though:

Public Enum CurrentStatus
    Good
    Bad
End Enum

Public Class StatusEventArgs
    Inherits EventArgs
    Private _currentStatus As CurrentStatus

    Public Property CurrentStatus() As CurrentStatus
        Get
            Return _currentStatus
        End Get
        Set(ByVal value As CurrentStatus)
            _currentStatus = value
        End Set
    End Property
End Class

Public Class StatusClass
    Public Event StatusChanged As EventHandler(Of StatusEventArgs)

    Protected Overridable Sub OnStatusChanged(ByVal newStatus As CurrentStatus)
        Dim s As New StatusEventArgs()
        s.CurrentStatus = newStatus
        RaiseEvent StatusChanged(Me, s)
    End Sub
End Class

Public Class SomeClass
    Private _status As StatusClass
    Public Event StatusChanged As EventHandler(Of StatusEventArgs)

    Protected Overridable Sub OnStatusChanged(ByVal newStatus As CurrentStatus)
        Dim s As New StatusEventArgs()
        s.CurrentStatus = newStatus
        RaiseEvent StatusChanged(Me, s)
    End Sub

    Public Property Status() As StatusClass
        Get
            Return _status
        End Get
        Set(ByVal value As StatusClass)
            If Not _status Is Nothing Then
                RemoveHandler _status.StatusChanged, AddressOf StatusHandler
            End If

            _status = value

            If Not _status Is Nothing Then
                AddHandler _status.StatusChanged, AddressOf StatusHandler
            End If
        End Set
    End Property

    Private Sub StatusHandler(ByVal sender As Object, ByVal e As StatusEventArgs)
        OnStatusChanged(e.CurrentStatus)
    End Sub
End Class
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号