Writing the Logic Using Visual Basic
With the UI built, it's time to write the code to make it do something usefulfor instance, display the current time in the button.
Double-click the Page.xaml.vb file in Solution Explorer to load it in the code editor.
|Figure 14. Handlers: Creating the event handler for the Completed event.|
In the Page_Loaded() subroutine, add the following bolded lines:
Partial Public Class Page
Public Sub Page_Loaded(ByVal o As Object, ByVal e As EventArgs)
' Required to initialize variables
Me.Timeline1.Duration = New Duration(New TimeSpan(0, 0, 1))
In the preceding code, the Timeline1
triggers an event (the Completed
event) each second (set through the Duration
object). The Timeline
object is somewhat similar to the Timer
control that Windows developers are familiar with. The Begin()
method starts the countdown and one second later the Completed
event is fired.
The next step would be to service the Completed event, which you can easily do by first selecting the Timeline1 object from the top of the code editor, and then selecting its corresponding Completed event (see Figure 14).
|Figure 15. Completed: Testing the application in both IE and FireFox.|
Code the Completed event handler as follows:
Private Sub Timeline1_Completed( _
ByVal sender As Object, _
ByVal e As System.EventArgs) _
Dim textBlk As TextBlock = Me.btnTime.Children(1)
textBlk.Text = Now.ToString
Basically, you set the current time by retrieving the TextBlock
control embedded within the canvas (btnTime
) and setting its Text
property. The canvas has two children:
- Children(0): Rectangle control
- Children(1): TextBlock control
After displaying the time, you call the Begin()
method to start the countdown again.
That's it! Press F5 in Visual Studio 2008 and you will see your Silverlight application displayed in Internet Explorer. If you load the sample application in FireFox, it will look and work the same (see Figure 15). The button will update the time every second.