Silverlight Global Properties

January 8, 2009 13:16 by wjchristenson2

It took me awhile to figure out the best way to create objects that can be used application-wide in Silverlight.  I'll quickly show you how easy it is to do so.

Let's say we want a global property that stores when the Silverlight application was first started.  We will acquire the date/time on application startup and store its value in our application object (App.xaml code behind) via a property.  Here's the code to do so in my App.xaml.vb file:


   1:      Private _startDateTime As Date
   2:   
   3:      Public ReadOnly Property StartDateTime() As Date
   4:          Get
   5:              Return _startDateTime
   6:          End Get
   7:      End Property
   8:   
   9:      Private Sub Application_Startup(ByVal o As Object, ByVal e As StartupEventArgs) Handles Me.Startup
  10:          _startDateTime = Date.Now
  11:          Me.RootVisual = New Page()
  12:      End Sub


When my RootVisual (page) loads, I'll get a handle on the current application object and set a TextBlock's text to the applications startup time which is stored in our application's property we defined.  Here's the code to do so:


   1:      Private Sub Page_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded
   2:          Me.tbkDate.Text = DirectCast(Application.Current, App).StartDateTime.ToShortDateString() & " " & DirectCast(Application.Current, App).StartDateTime.ToShortTimeString()
   3:      End Sub

In line 2, we get a handle on the current application object by casting "Application.Current" to our "App" type.  Once we have this, we can access our newly created property and set our TextBlock's text property to it.

SilverlightGlobal_Soln.zip (583.88 kb)