Bind your Silverlight elements to local variables

by rahul 3/1/2011 11:25:32 PM

So you have a XAML page, and in the code behind you have a couple of variables. How do you bind the elements with the local variables?

    To begin with, you will need the property with which you can bind the XAML element.
    Implement the following interface… INotifyPropertyChanged

       public event PropertyChangedEventHandler PropertyChanged;
       private void NotifyPropertyChanged(String info)
           if (PropertyChanged != null)
               PropertyChanged(this, new PropertyChangedEventArgs(info));

       int _hour;
       public int Hour
           get { return _hour; }
           set {
               if (value != _hour)
                   _hour = value;

    Inside the constructor of your page, add the following line…

         this.DataContext = this;

    Now, bind as usual…

<TextBlock Text="{Binding Hour}" />

    Yep, that simple!

Until next time, Wave


Quote of the day:
Sometimes what's right isn't as important as what's profitable. - Trey Parker and Matt Ston



blog comments powered by Disqus

Who is Rahul?


He likes to troubleshoot IIS and SharePoint Performance issues.

Freelance Consultant.

Founder - AttoSol Technologies.


The opinions expressed herein are our own personal opinions and do not represent our employer's view in any way.
© Copyright 2015, Rahul Soni