Silverlight 2.0 DataBinding Explained (a bit) :)

 

Silverlight supports data binding, but currently there is a lack of samples explaining some of the nicer concepts, plus some of the things are not as you might expect.

Data binding in Silverlight is through the {Binding <Path>} syntax, for example to bind a TextBox's Text property to the Value property of some class you would use

<TextBox Text="{Binding Value}"  />

The catch is that this is a one way binding, if you change the Text in the TextBox the Age property doesn't get updated...

The solution is simple, you need to set the Mode property of the Binding object to TwoWay like this:

<TextBox Text="{Binding Value, Mode=TwoWay}"  />

Now modifying the Text property will modify the Value property (and vice versa).

Next on my agenda is data conversion. You can do this by using a class that implement the IValueConverter interface, for example:

public class DoubleToBrushConverter  : IValueConverter {   public object Convert(object value, Type targetType, object parameter, CultureInfo culture)   {     string v = (value ?? "0").ToString();     double cutoff = parameter == null ? 30 : double.Parse( parameter.ToString() );      if (double.Parse(v) < cutoff)       return new SolidColorBrush(Colors.Green);     else       return new SolidColorBrush(Colors.Red);   }    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)   {     throw new NotImplementedException();   } } 

This class will convert the value to a brush, nice if you want to show the user that an invalid or unusual value was entered. You can use this as follows:

<TextBox Text="{Binding Value, Mode=TwoWay}"           Background="{Binding Value,                                Converter={StaticResource converter},                               ConverterParameter=40}" /> 

The ConverterParameter will get passed into the Convert method as the parameter parameter.

Please note that we don't need to implement the ConvertBack method of the IValueConverter interface because the user will not be able to change the background color.

image

When the value goes above 40 the background turns red.

Last thing is the Source property of the Binding element. With this you can point to some object on your Page, stored as a resource:

<TextBox Text="{Binding Value, 
                  Mode=TwoWay, 
                  Source={StaticResource someObject}}"  />

 

This of course opens up using Element binding, which means binding to elements of your page to each other. The technique I propose is using some temporary object and binding the controls to this object.

For example, to bind three controls (two textboxes and one slider) to each other use following markup:

<TextBox Text="{Binding Value, Mode=TwoWay, Source={StaticResource someObject}}"  /> <TextBox Text="{Binding Value, Mode=TwoWay, Source={StaticResource someObject}}"           Background="{Binding Value,                               Source={StaticResource someObject},                               Converter={StaticResource converter},                                ConverterParameter=40}" />  <Slider x:Name="theSlider"   Minimum="0" Maximum="100" SmallChange="1" LargeChange="10"     Value="{Binding Value, Mode=TwoWay, Source={StaticResource someObject}}" /> 

Each binding refers to the same Source, which I've declared on top of the page resources:

<UserControl.Resources>   <u:DoubleToBrushConverter x:Key="converter" />   <u:ElementBinding x:Key="someObject" Value="66" /> </UserControl.Resources> 

The DoubleToBrushConverter class is the one on top, the ElementBinding class looks like this:

public class ElementBinding : INotifyPropertyChanged {   double val;    public double Value   {     get { return val; }     set { val = value; OnPropertyChanged("Value"); }   }    public event PropertyChangedEventHandler PropertyChanged;    protected virtual void OnPropertyChanged(string propName)   {     if (PropertyChanged != null)       PropertyChanged(this, new PropertyChangedEventArgs(propName));   } } 

The class implements the standard INotifyPropertyChanged interface to support databinding.

A demo project containing this sample can be found here.


Comments (10) -

July 11. 2008 05:48 AM

Hello Peter,  I was wondering how to do databinding between the properties of two controls in Silverlight. After reading your post I know that looking for a solution in XAML is futile and that this is a scenario that is only supported in WPF.  And thanks for posting a solution. This is helpfull when one needs to databind many properties to the same value. But it is pity that there is no simple solution when one just wants to databind the properties of two controls, creating an ElementBinding class is a little bit too much work.  Maybe this can be solved by  1) making the ElementBinding class generic 2) or, even better, extending the Binding mechanism and binding expressions of Silverlight so that it also supports Element binding (basically implementing this feature of WPF oneself). Do you think that it is possible to extend Binding in such a way ?  greetings from Norway, Stefaan

December 18. 2009 12:27 AM

teeth whitening gels

Me and my friend were arguing about an issue similar to this! Now I know that I was right. lol! Thanks for the information you post.

teeth whitening gels

December 18. 2009 05:01 AM

BBQ Grill Recipes

Just wanted to give you a shout from the valley of the sun, great information. Much appreciated.

BBQ Grill Recipes

December 19. 2009 09:50 AM

IT contractor accountants

Hrmm that was weird, my comment got eaten. Anyway I wanted to say that it's nice to know that someone else also mentioned this as I had trouble finding the same info elsewhere. This was the first place that told me the answer. Thanks.

IT contractor accountants

December 22. 2009 11:55 AM

rochester attorney

Howdy, i read your blog occasionally and i own a similar one and i was just wondering if you get a lot of spam comments? If so how do you prevent it, any plugin or anything you can advise? I get so much lately it's driving me mad so any assistance is very much appreciated.

rochester attorney

January 9. 2010 05:50 PM

dog training

This article gives the light in which we can observe the reality. this is very nice one and gives indepth information. thanks for this nice article

dog training

January 14. 2010 10:47 PM

CNA Training

Thank you for the sensible critique. Me & my neighbour were preparing to do some research about that. We got a good book on that matter from our local library and most books where not as influensive as your information. I am very glad to see such information which I was searching for a long time.This made very glad Smile

CNA Training

January 15. 2010 03:48 AM

food science

I admire what you have done here. I like the part where you say you are doing this to give back but I would assume by all the comments that this is working for you as well.

food science

January 20. 2010 07:05 PM

NJ Website Design

Well, this is my first visit to your blog! We are a group of volunteers and starting a new initiative in a community in the same niche. Your blog provided us valuable information to work on. You have done a marvellous job!

NJ Website Design

January 24. 2010 12:56 AM

roulette system

Just wanted to give you a shout from the valley of the sun, great information. Much appreciated.

roulette system

January 25. 2010 04:46 PM

rockhopper tracker

Couldn?t be written any better. Reading this post reminds me of my old room mate! He always kept talking about this. I will forward this article to him. Pretty sure he will have a good read. Thanks for sharing!

rockhopper tracker

January 28. 2010 08:55 PM

avg free

Aw, this was a really quality post. In theory I'd like to write like this too - taking time and real effort to make a good article... but what can I say... I procrastinate alot and never seem to get something done.

avg free

January 30. 2010 12:46 AM

contractor accountants

Do you accept guest posts? I would love to write couple articles here.
I was wondering what is up with that weird gravatar??? I know 5am is early and I'm not looking my best at that hour, but I hope I don't look like this! I might however make that face if I'm asked to do 100 pushups. lol

contractor accountants

January 31. 2010 05:05 PM

HO Scale Trains

Hello,I love reading through your blog, I wanted to leave a little comment to support you and wish you a good continuation. Wishing you the best of luck for all your blogging efforts.

HO Scale Trains

February 3. 2010 11:00 PM

assurance hypothecaire

Have you ever considered adding more videos to your blog posts to keep the readers more entertained? I mean I just read through the entire article of yours and it was quite good but since I'm more of a visual learner,I found that to be more helpful well let me know how it turns out! I love what you guys are always up too. Such clever work and reporting! Keep up the great works guys I've added you guys to my blogroll. This is a great article thanks for sharing this informative information.. I will visit your blog regularly for some latest post.

assurance hypothecaire

February 6. 2010 09:32 PM

how to tie a tie step by step

Hi webmaster, commenters and everybody else !!! The blog was absolutely fantastic! Lots of great information and inspiration, both of which we all need!b Keep 'em coming... you all do such a great job at such Concepts... can't tell you how much I, for one

how to tie a tie step by step

February 8. 2010 12:55 PM

merchant funding

You got a really useful blog I have been here reading for about an hour. I am a newbie and your success is very much an inspiration for me.

merchant funding

February 10. 2010 05:04 AM

inground swimming pool cleaners

While this subject can be very touchy for most people, my opinion is that there has to be a middle or common ground that we all can find. I do appreciate that youve added relevant and intelligent commentary here though. Thank you!

inground swimming pool cleaners

February 10. 2010 08:36 AM

outdoor gazebo

Hi webmaster, commenters and everybody else !!! The blog was absolutely fantastic! Lots of great information and inspiration, both of which we all need!b Keep 'em coming... you all do such a great job at such Concepts... can't tell you how much I, for one appreciate all you do!

outdoor gazebo

February 13. 2010 06:26 AM

game downloads

Aw, this was a really quality post. In theory I'd like to write like this too - taking time and real effort to make a good article... but what can I say... I procrastinate alot and never seem to get something done.

game downloads

February 13. 2010 02:40 PM

Union City Garage Door Repair

Hrmm that was weird, my comment got eaten. Anyway I wanted to say that it's nice to know that someone else also mentioned this as I had trouble finding the same info elsewhere. This was the first place that told me the answer. Thanks.

Union City Garage Door Repair

February 15. 2010 02:24 PM

best acne treatment

Howdy, i read your blog occasionally and i own a similar one and i was just wondering if you get a lot of spam comments? If so how do you prevent it, any plugin or anything you can advise? I get so much lately it's driving me mad so any assistance is very much appreciated.

best acne treatment

February 24. 2010 08:32 AM

make money online

This is a really good read for me, Must admit that you are one of the best bloggers I ever saw.Thanks for posting this informative article.

make money online

February 25. 2010 09:52 PM

electronic cigarette

I must say that overall I am really impressed with this blog.It is easy to see that you are passionate about your writing. If only I had your writing ability I look forward to more updates and will be returning.

electronic cigarette

February 26. 2010 03:10 AM

trout lures

Couldn?t be written any better. Reading this post reminds me of my old room mate! He always kept talking about this. I will forward this article to him. Pretty sure he will have a good read. Thanks for sharing!

trout lures

March 9. 2010 05:19 AM

Pamula Roybal

Good site, where did you come up with the information in this posting? Im pleased I found it though, ill be checking back soon to see what other articles you have.

Pamula Roybal

March 15. 2010 09:45 PM

Berry Vasko

This is a good posting, I was wondering if I could use this summary on my website, I will link it back to your website though. If this is a problem please let me know and I will take it down right away.

Berry Vasko

September 21. 2011 06:14 PM

Jordan Shoes

According to a recent survey, four million people die each year from diseases linked to smoking.

Jordan Shoes

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading

Download the U2U brochure

Download Brochure

Receive the U2U Newsletter. Submit your email address:
 
 


 


Search

rss  RSS

Archive