An object-oriented programming language developed by Microsoft that can be used in .NET.
Just like in UpdateClock, you need to use Dispatcher.Invoke() to call RaiseEvent PropertyChanged so it runs on the ui thread.
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
My application includes a stopwatch plus a lap counter. The stopwatch is working fine using the following code:
Private Sub StartTimer(sender As Object, e As RoutedEventArgs) Handles btnStart.Click
CurrentTime = TimeSpan.Zero
LapTime = TimeSpan.Zero
LapCount = 0
tmr = New Timer(1000) With {.Enabled = True}
AddHandler tmr.Elapsed, AddressOf UpdateClock
End Sub
Private Sub UpdateClock(source As Object, e As ElapsedEventArgs)
Dispatcher.Invoke(Sub() PopulateTimer())
End Sub
Private Sub PopulateTimer()
CurrentTime = CurrentTime.Add(OneSecond)
txtDuration.Text = CurrentTime.ToString
End Sub
Saving laps uses this code:
Public Property Laps As List(Of Lap)
Private Sub CreateLap(sender As Object, e As RoutedEventArgs) Handles btnLap.Click
Dim t As Task = Task.Run(
Sub()
SaveLap()
End Sub)
End Sub
Private Sub SaveLap()
LapTime = CurrentTime - LapTime
LapCount += 1
Laps.Add(New Lap With {.Count = LapCount, .Duration = LapTime})
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(NameOf(Laps)))
LapTime = CurrentTime
End Sub
The XAML for showing laps is as follows:
<DataGrid
x:Name="dgLaps"
AutoGenerateColumns="False"
ItemsSource="{Binding Path=Laps}"
Margin="0,0,10,0">
<DataGrid.Columns>
<DataGridTextColumn
Binding="{Binding Path=Count}"
Header="Lap"
Width="30" />
<DataGridTextColumn
Binding="{Binding Path=Duration}"
Header="Duration"
Width="*" />
</DataGrid.Columns>
</DataGrid>
This all works - for the first lap. After that, the SaveLap subroutine is processed but the additional laps are not displayed in the DataGrid. I have confirmed that Laps does contain all the added laps so that is not the problem. Why does the code only work once?
An object-oriented programming language developed by Microsoft that can be used in .NET.
Just like in UpdateClock, you need to use Dispatcher.Invoke() to call RaiseEvent PropertyChanged so it runs on the ui thread.