This post is about a simple application that I’ve created to get my hands on Silverlight 2. It is simple Digital Clock which shows local time using custom fonts and updates itself every second. My few observations that I would like to share with you:

Demo Application

  1. Custom Font Embedding in Silverlight
  2. Data Binding Modes and using INotifyPropertyChanged
  3. Using Dispatcher.BeginInvoke()

Before we start digging each of above topics lets first have a look at the application in running condition. I have named it SilverTimer.


Download: SilverTimer Source (C#/VS 2008)


Custom Font Embedding in Silverlight

I have used custom fonts (courtesy: DS-DIGI.TTF) in my SilverTimer application. These fonts are first downloaded automatically by the Silverlight Runtime. Here is excerpt showing how to embedd custom fonts –


FontFamily is comprise of this format – FONT_FILE#FONT_NAME. Having said that font file is “DS-DIGI.TTF” and the font named “DS-Digital” and are separated by‘#’. The real beauty is that we need not write any single line of code for downloading the font-file. Just keep DS-DIGI.TTF file “ClientBin” folder where the XAP file is located. One thing to note here is that before you use custom font you need to change the Build Action for your Font file to ‘Resource’ as shown below. This will make it as an assembly resource.

Digital_prop

This is all you have to do to use the custom fonts. If you wish to know more about custom font embedding, you can watch this great video tutorial by Tim Heuer

Data Binding Modes and using INotifyPropertyChanged

I’d like to discuss it in three basic Steps

  1. Specifying DataBinding Mode
  2. Set the DataContext
  3. Implement INotifyPropertyChanged interface to the business object

Silverlight supports binding of Business Object properties with the UI Controls. The data flow between these can be controlled by specify the Data Binding Mode between source and target. Here source is the Business Object and target is the UI control. Modes supported are –

OneWay” – Binds source and target and update target subsequently as the source gets updated. (source -> target)
TwoWay” – It keeps source and target in sync. Source is updated when a target changed and vice versa. (source <-> target)
OneTime” – As the name suggest, it updates target with the data and never updates when a source get updated.

In application, I’ve used ‘OneWay’ Binding Mode to update the Time in application. Below is the excerpt from Page.xaml –


Here we are talking about this bit  “Text=”{Binding CurrentTime, Mode=OneWay}”, You can see the Text property is bind to the CurrentTime property and the mode is defined as ‘OneWay’.

Now, we need to specify which Object this property is associated with. We have to set the DataContext of target control to the Business Object. It goes like this –

txtTimer.DataContext = objTimer;

Specifying the Mode doesn’t do the job we need some mechanism/event which tells the UI controls (TextBlock) to update itself when a property of business object changed. This can be achieved by implementing the INotifyPropertyChanged interface to the business object. The INotifyPropertyChanged interface is used to notify clients, typically binding clients, that a property value has changed. In this case Timer.cs is the business object that implemented this interface and should raise a PropertyChanged event when “CrrentTime” is changed. –

        public string CurrentTime
        {
            get
            {
                return currentTime;
            }
            set
            {
                currentTime = value;
                if (PropertyChanged != null)
                {
                    PropertyChanged(this,new PropertyChangedEventArgs("CurrentTime"));
                }
            }
        }
  .. .. ..

Whenever the CurrentTime property changed it notify the clients and they will be updated accordingly. You can go through this excellent video tutorial by Jesse Liberty

Using Dispatcher.BeginInvoke()

Dispatcher.BeginInvoke is used to execute the delegate asynchronously. Dispatcher is associated with the thread which is UI thread in this case. Why we need to use this? Form controls should be accessed in a thread which they have been created. Doing otherwise may throw “Invalid Cross-thread access” exception.

So, as soon as “CurrentTime” property is changed, the binding controls will be notified which is trigger by the “PropertyChanged Event” of “INotifyPropertyChanged” interface. But as this happen in a new thread this cause “Invalid Cross-thread access” exception.

The key to resolve this error is to update the “CurrentTime” property using dispatcher which guarantees the code to be executed on UI thread.

         public void RunTimer(object oDispatch)
        {
            while (true)
            {
                // Making asynchronous call to update the Texblock using the UI Thread.
                ((Dispatcher)oDispatch).BeginInvoke(() =>
                   {
                       //Updating the property which inturn notify the clients to udpate.
                       this.CurrentTime = System.DateTime.Now.ToLongTimeString();
                   }
               );

                // New thread sleeps for one second.
                System.Threading.Thread.Sleep(1000);
            }
        }

I hope you may have find this information useful. I would like to hear your comments and queries on this.

ShareTweet about this on TwitterShare on LinkedInShare on Google+Share on RedditShare on StumbleUponShare on FacebookEmail this to someone
A Simple Silverlight Application

5 thoughts on “A Simple Silverlight Application

  • April 16, 2009 at 8:21 pm
    Permalink

    Thanks for article. very informative.

  • April 19, 2009 at 2:08 am
    Permalink

    I want to make this as a desktop application with Silverlight3. Thanks for the article 🙂

  • February 3, 2011 at 5:25 pm
    Permalink

    Whats up this is somewhat of off topic but I was wanting to know if blogs use WYSIWYG editors or if you have to manually code with HTML. I’m starting a blog soon but have no coding expertise so I wanted to get guidance from someone with experience. Any help would be greatly appreciated!

  • February 9, 2011 at 7:02 am
    Permalink

    HI, This is what I has been looking for!!

    showing time is just a small part but very important for bussiness application what I’m making ,

    Thank you.

  • November 14, 2011 at 3:32 am
    Permalink

    you explanation is misleading….the reason currentime wont get updated with dispatcher.begininvoke is bcoz u r trying to update UI element from a background thread.

Leave a Reply

Your email address will not be published. Required fields are marked *