George George - 7 months ago 58 Question

Trying to create countdown Timer in WPF

I am trying to create a timer for when my xaml page loads it starts a four minute timer and when it gets to 0 have the program stop and start again. having an issue creating the timer. Using DispatcherTimer in to get result. Code below:

Private Sub Timer_Loaded(sender As Object, e As RoutedEventArgs)
Dim time = New Threading.DispatcherTimer()
time.Interval = New TimeSpan(0, 0, 1)
AddHandler time.Tick, AddressOf time_tick
End Sub

Public Sub time_tick(ByVal sender As Object, e As RoutedEventArgs)
Timer.Text = Date.Now.Second
End Sub

Tried putting the time_click as a public sub as doing it inside of the Timer_Loaded xaml event would throw an error. I get the following error when running the code:

System.InvalidCastException: 'Unable to cast object of type 'System.EventArgs' to type 'System.Windows.RoutedEventArgs'.'

Googled a couple fixes, and tried rewriting the timer function. However I can't get passed this issue. Also tried putting the content tag of the text box right in the address of however the Address of only takes methods.

Answer Source

A handler of the DispatcherTimer's Tick event only accepts an event argument of type System.EventArgs:

Public Sub time_tick(ByVal sender As Object, e As EventArgs)
    Timer.Text = Date.Now.Second
End Sub

Check out this outstanding article on the topic:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download