Wpf – Subscribing events in VB.NET

eventsvb.netwpf

I'm trying to convert some C# code to VB.NET.

I have the following in C# (which works)

m_switchImageTimer = new DispatcherTimer();
m_switchImageTimer.Interval = Interval;
m_switchImageTimer.Tick += (s, e) => LoadNextImage();

The key line I'm struggling to convert successfully is:

m_switchImageTimer.Tick += (s, e) => LoadNextImage();

What I have tried is:

m_switchImageTimer.Tick += Function(s, e) LoadNextImage()
m_switchImageTimer.Tick += New EventHandler(AddressOf LoadNextImage)

Neither of these are working.

The first attempt produces two errors, the first VS2010 highlights under m_switchImageTimer.Tick:

Error 1 'Public Event Tick(sender As Object, e As System.EventArgs)' is an event, and cannot be called directly. Use a 'RaiseEvent' statement to raise an event

and highlighted under LoadNextImage() produces the following error:

Error 3 Expression does not produce a value.

The second attempt produces the same error:

Error 1 'Public Event Tick(sender As Object, e As System.EventArgs)' is an event, and cannot be called directly. Use a 'RaiseEvent' statement to raise an event.

How can I convert the C# code to VB.NET?

Thanks
Ben

Best Answer

Subscribing to events in VB.NET requires either the AddHandler or Handles keyword. You will also have a problem with the lambda, the Function keyword requires an expression that returns a value. In VS2010 you can write this:

    AddHandler m_switchImageTimer.Tick, Sub(s, e) LoadNextImage()

In earlier versions, you need to either change the LoadNextImage() method declaration or use a little private helper method with the correct signature:

    AddHandler m_switchImageTimer.Tick, AddressOf SwitchImageTimer_Tick
...
Private Sub SwitchImageTimer_Tick(sender As Object, e As EventArgs)
    LoadNextImage()
End Sub
Related Topic