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;
                   NotifyPropertyChanged("Hour");
               } 
           }
       }

    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
Rahul

 

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

Rahul Soni

Rahul Soni  Twitter

 LinkedIn

 Facebook

 Email me



Vivek Kumbhar

Vivek Kumbhar  Twitter

 LinkedIn

 Facebook

 Email me


Stack Exchange

profile for Vivek at Server Fault, Q&A for system administrators and IT professionals

profile for Rahul Soni at Stack Overflow, Q&A for professional and enthusiast programmers

Calendar

<<  May 2013  >>
MoTuWeThFrSaSu
293012345
6789101112
13141516171819
20212223242526
272829303112
3456789

View posts in large calendar

All Items
Sign in

Visit Microsoft's Site

Disclaimer

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

Powered by BlogEngine.NET 1.4.5.0