Silverlight
How to: Create a Timer
To create a timer in Silverlight, use the DispatcherTimer class in the System.Windows.Threading namespace.
The following example shows a simple counter that uses a DispatcherTimer.
Example
XAML
<Grid x:Name="LayoutRoot" Background="White"> <!-- Just a TextBlock to show the output of the timer. --> <TextBlock Loaded="StartTimer" x:Name="myTextBlock" /> </Grid>
C#
public void StartTimer(object o, RoutedEventArgs sender) { System.Windows.Threading.DispatcherTimer myDispatcherTimer = new System.Windows.Threading.DispatcherTimer(); myDispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 100); // 100 Milliseconds myDispatcherTimer.Tick += new EventHandler(Each_Tick); myDispatcherTimer.Start(); } // A variable to count with. int i = 0; // Raised every 100 miliseconds while the DispatcherTimer is active. public void Each_Tick(object o, EventArgs sender) { myTextBlock.Text = "Count up: " + i++.ToString(); }
Visual Basic
Public Sub StartTimer(ByVal o As Object, ByVal sender As RoutedEventArgs)
Dim myDispatcherTimer As System.Windows.Threading.DispatcherTimer = New System.Windows.Threading.DispatcherTimer
myDispatcherTimer.Interval = New TimeSpan(0, 0, 0, 0, 100)
' 100 Milliseconds
AddHandler myDispatcherTimer.Tick, AddressOf Me.Each_Tick
myDispatcherTimer.Start
End Sub
' A variable to count with.
Private i As Integer = 0
' Raised every 100 miliseconds while the DispatcherTimer is active.
Public Sub Each_Tick(ByVal o As Object, ByVal sender As EventArgs)
("Count up: " + i) = (("Count up: " + i) _
+ 1)
myTextBlock.Text = ("Count up: " + i)
ToString
End Sub
Community Content
devnw
Code Translator
It looks as if whomever wrote the code in C# just used a C# to VB translator. That would explain why the VB code is incorrect in such a noticeable way.
asritha.reddy
Above coding is wrong
That should be
$0$0
$0
$0 myTextBlock.Text = "Count up: " & System.Math.Max(System.Threading.Interlocked.Increment(i), i - 1).ToString()$0
asritha.reddy
Above coding is wrong
That should be
$0$0
$0
$0 myTextBlock.Text = "Count up: " & System.Math.Max(System.Threading.Interlocked.Increment(i), i - 1).ToString()$0
asritha.reddy
Above coding is wrong
That should be
$0$0
$0
$0 myTextBlock.Text = "Count up: " & System.Math.Max(System.Threading.Interlocked.Increment(i), i - 1).ToString()$0
asritha.reddy
Above coding is wrong
The text should be as follows
myTextBlock.Text = "Count up: " & System.Math.Max(System.Threading.Interlocked.Increment(i), i - 1).ToString()
$0
CorySmith
Fix VB sample.
The code in the Each_Tick routine for VB should read something more like:
myTextBlock.Text = "Count up: " + i.ToString() : i += 1