.NET Blog

Tony Cavaliere

 
My Favourite Albums
  And the Grappa wins.
E-mail me Send mail
Add to Technorati Favorites AddThis Feed Button

Subscribe to Cynot Why Not


Recent posts

Disclaimer

Hey unlike other bloggers I stand by what I say but just in case. The opinions expressed herein are my own except on Tuesday when the second card is not turned up otherwise it ain't worth squat.

© Copyright 2010

Silverlight Data Binding, using INotifyPropertyChanged and ObservableCollection

Silverlight is a subset of WPF and it is no surprise that Silverlight's data binding model borrows from WPF. Both technologies use the INotifyPropertyChanged interface and ObservableCollection generic to easily incorporate two way data binding into an application. A CLR object that implements the INotifyPropertyChanged interface and raises a PropertyChanged event whenever a bindable property changes is easily added into the XAML using the binding syntax. Listing 1 shows how to create a class that implements INotifyPropertyChanged and raises the PropertyChanged event. Listing 2 shows how to bind the properties to Text boxes in XAML.

Listing 1: Implementing the INotifyPropertyChanged Interface

    1 Imports System.ComponentModel

    2 

    3 Public Class Person

    4     Implements INotifyPropertyChanged

    5 

    6     Public Event PropertyChanged(ByVal sender As Object, _

    7         ByVal e As System.ComponentModel.PropertyChangedEventArgs) _

    8         Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged

    9 

   10     Private Sub FirePropertyChanged(ByVal [property] As String)

   11         If Not String.IsNullOrEmpty([property]) Then

   12             RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs([property]))

   13         End If

   14     End Sub

   15 

   16     Private _Name As String

   17     Public Property Name() As String

   18         Get

   19             Return _Name

   20         End Get

   21         Set(ByVal value As String)

   22             _Name = value

   23             FirePropertyChanged("Name")

   24         End Set

   25     End Property

   26 

   27     Private _Count As Integer

   28     Public Property Count() As Integer

   29         Get

   30             Return _Count

   31         End Get

   32         Set(ByVal value As Integer)

   33             _Count = value

   34             FirePropertyChanged("Count")

   35         End Set

   36     End Property

   37 

   38     Public Sub New(ByVal name As String, ByVal count As Integer)

   39         Me.Name = name

   40         Me.Count = count

   41     End Sub

   42 

   43 End Class

Listing 2: XAML Data Binding syntax

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

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

All that is needed is to set the DataContext of a parent container to an instance of the Person object and that's it, you now have two way data binding. Whenever the underlying object is modified the UI will automatically be updated and whenever the UI is changed the object is updated. Now that's pretty simple.

Now what if we need to bind a collection to a data grid, combo box or even a chart? You could write a custom collection class that implements INotifyPropertyChanged or better yet you can use the ObservableCollection generic class, which already implements the INotifyPropertyChanged. Listing 3 uses the ObservableCollection generic to create a collection of the above Person class.

Listing 3: Using the ObservableCollection Generic

   13     Private members As New ObservableCollection(Of Person)

   14 

   15     Private Sub Page_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) _

   16         Handles Me.Loaded

   17         members.Add(New Person("Tony", 5))

   18         members.Add(New Person("Sally", 2))

   19         members.Add(New Person("John", 8))

   20         grid.ItemsSource = members

   21         comboBoxName.ItemsSource = members

   22         CType(chart.Series(0), DynamicSeriesWithAxes).ItemsSource = members

   23     End Sub

The above snippet also includes how to bind the collection to a data grid, chart and combo box. The XAML used to bind this collection to the previously mentioned controls is shown in Listing 4.

Listing 4: Xaml Binding syntax for Datagrid, Chart and ComboBox

   17         <data:DataGrid x:Name="grid" Grid.Row="1" Grid.Column="0" AutoGenerateColumns="False" >

   18             <data:DataGrid.Columns>

   19                 <data:DataGridTextColumn Header="Name" FontSize="20" Width="185"

   20                   Binding="{Binding Mode=TwoWay, Path=Name}" />

   21                 <data:DataGridTextColumn Header="Count" FontSize="20" Width="188"

   22                   Binding="{Binding Mode=TwoWay, Path=Count}" />

   23             </data:DataGrid.Columns>

   24         </data:DataGrid>

   38         <charting:Chart x:Name="chart" Grid.Row="2" Grid.Column="0">

   39             <charting:Chart.Series>

   40                 <charting:ColumnSeries

   41                    DependentValueBinding ="{Binding Mode=TwoWay, Path=Count}"

   42                    IndependentValueBinding ="{Binding Mode=TwoWay, Path=Name}" />

   43             </charting:Chart.Series>

   44         </charting:Chart>

   49         <ComboBox x:Name="comboBoxName" Width="150" Height="25" HorizontalAlignment="Left" Margin="10,0,0,0">

   50              <ComboBox.ItemTemplate>

   51                   <DataTemplate>

   52                          <TextBlock Text="{Binding Path=Name}" FontSize="16"/>

   53                   </DataTemplate>

   54              </ComboBox.ItemTemplate>

   55          </ComboBox>

With this binding in place we get out of the box two way data binding, that is, if the underlying collection of person objects is modified it is automatically reflected in the UI elements that are bound to it. Likewise if the UI is changed then the underlying collection is also modified. Now that is pretty cool.

If you are interested in the complete source code, please visit my Silverlight gallery there you can see in action two Silverlight data binding applications. Just select Databinding 1 and Databinding 2 from the menu. The first, demos data binding to simple object and the second, demos data binding to a collection of objects. As always the source code to every demo on the gallery is available for download.

Enjoy!

If you are wondering about the chart and expander controls in Databinding 2 gallery demo then visit this codeplex site.

This post was inspired by Jigar Desai post. Check it out.

Guess the movie

I wish I could do something about this. But I can't. But I can promise you two things. One: I'll always look this good. Two: I'll never give up on you... ever.

Currently rated 5.0 by 2 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: Silverlight
Posted by CynotWhyNot on Monday, November 03, 2008 4:55 PM
Permalink | Comments (24) | Post RSSRSS comment feed

Related posts

Comments

how to pass a saliva drug test us

Friday, September 11, 2009 5:41 AM

how to pass a saliva drug test

I added your post to my college Report


Regards

Hens

aion kina us

Wednesday, September 16, 2009 3:06 PM

aion kina

Wonder full writing skills you got mate.


Regards
Mathu

aion kina us

Wednesday, September 16, 2009 3:06 PM

aion kina

Wonder full writing skills you got mate.


Regards
Look

aion kina us

Wednesday, September 16, 2009 4:43 PM

aion kina

I bookmarked your post will read this latter


Regards

Arvin

aion gold us

Wednesday, September 16, 2009 4:43 PM

aion gold

Hi nice POst

Regards

Cutie

RV carports us

Thursday, September 24, 2009 7:48 AM

RV carports

Wonder full writing skills you got mate.


Regards
Flashy

buy cheap aion gold us

Thursday, October 08, 2009 7:16 AM

buy cheap aion gold

I posted your blog to my facebook group


Regards

hanitz

aion online item us

Thursday, October 08, 2009 7:16 AM

aion online item

I added your post to my college Report


Regards

saniths

life insurance rates us

Friday, October 09, 2009 2:12 AM

life insurance rates

I added your post to my college Report


Regards

Wright

Greek Wine us

Wednesday, November 18, 2009 3:05 AM

Greek Wine

I will bookmark and continue reading your blog in the future! Thanks alot for the informative post!


Regards
Bowe


Laboratory Equipment us

Friday, November 20, 2009 11:47 PM

Laboratory Equipment

Hi nice POst

Regards

Bushan

discount designer handbag US

Tuesday, December 01, 2009 10:33 PM

discount designer handbag

I really appreciate this wonderful post that you have provided for us. I assure this would be beneficial for most of the people.

adidas shoes US

Thursday, December 24, 2009 4:38 PM

adidas shoes

Hey, guy, your blog is nice. It can bring me many useful information.

discount designer handbags US

Thursday, December 31, 2009 12:18 PM

discount designer handbags

If you need to buy discount gucci bags, you can just type bagsvendor.com in you browser address line and find out the gucci bags on big sale in discounted price. The information below is only introducing the discount news about gucci bags and gucci handbags. A woman leads the world accounting her gucci bag. But then we must also remember that there is a well discount news that has to see. It is a common complaint that women having their share is not large enough to hold all your belongings necessary, such as discount gucci bags, designer bags. This gucci bags you can find in bagsvendor.com is that the person is unable to organize things properly. Each discount bag has a clear purpose and objects you choose to take the bag must be compatible with the purposes for which it is purchased in your mind. We can meet the wide range of needs that are part of the common things for a trip on a beautiful handbag, bags or purses. Thus, while the discounted gucci bags needs, here are some points that may be useful to organize the contents of the discount gucci bag. Even it is a discounted price gucci bags, but it has high quality. The quality of materials used with the gucci bag is leather, suede or cotton. These materials can be sure that they are not less than 100% authentic and of excellent quality discount bags. Accessories and decorative items from the discount gucci bag, such as hinges, chains, rings and belt buckles are higher that other bags. Some designers in the Gucci company will even give as a repair or replacement free of charge in a period of time to ensure that their discount handbags are offered in a different league than the shares that you can find at any mall or online store. Designer Gucci bags can be changed to discounted gucci bags. This is a big news about handbags on sale. Brands are just called by many famous fashion people, and can be done with any discounted news. Just find more in bagsvendor.com

air jordan US

Friday, January 01, 2010 11:12 PM

air jordan

In winnersneaker, these Nike Air Jordan shoes were associated with sport, fashion and basketball. The Nike Air Jordan sneakers were a way to hide some of the smaller sizes, or raise an important NBA star to even higher levels to the count. Nike Air Jordan shoes, but also less fashionable of Air Jordan history. Which were commonly used by high-ranking customers in NBA during the 19th century and were used in the 20th century to let the putrid mud in the streets, all you know is that you can find many discounted Air Jordan shoes in winnersneaker.com. Existing Air Jordan retro sneakers in the United States and Europe retails do not feel in fashion until the new Air Jordan shoes come in the street. At first the Air Jordan 1 shoes important wearing for young sport men, but once reigned basketball, Jordan shoes became the must-have fashion accessory for young people in the basketball playground. These Air Jordan original shoes were all to make a statement vividly. Air Jordans like Air Jordan 23 and Air Jordan 6 wore basketball shoes kiss in the context of his people larger than life. Wish you find a suitable Air Jordan shoes in winnersneaker.com.

discount handbags sale US

Sunday, March 07, 2010 4:04 PM

discount handbags sale

Hey, guy, your blog is nice. It can bring me many useful information.

designer handbags sale US

Monday, March 08, 2010 10:55 PM

designer handbags sale

You did the a great work writing and revealing the hidden beneficial features of BlogEngine.Net, that I found it was popularly used by bloggers nowadays. I think BE has emerged to be one of the best blogging platform right now. I wish you good luck with your blogging experiences.

discount designer handbag US

Tuesday, March 09, 2010 2:34 PM

discount designer handbag

Easily, the post is really the greatest on this laudable topic. I concur with your conclusions and will thirstily look forward to your future updates. Saying thanks will not just be sufficient, for the fantasti c lucidity in your writing. I will instantly grab your rss feed to stay privy of any updates. Solid work and much success in your business enterprize!

james sneakers US

Wednesday, March 10, 2010 9:45 PM

james sneakers

This is just the information I am finding everywhere. Thanks for your blog, I just subscribe your blog. This is a nice blog.

wholesale shoes from china US

Wednesday, March 10, 2010 11:28 PM

wholesale shoes from china

Substantially, the article is in reality the sweetest on this precious topic. I harmonise with your conclusions and will thirstily look forward to your upcoming updates. Saying thanks will not just be sufficient, for the phenomenal clarity in your writing. I will directly grab your rss feed to stay abreast of any updates. Pleasant work and much success in your business efforts!

designer handbag US

Thursday, March 11, 2010 2:48 AM

designer handbag

You did the a great work writing and revealing the hidden beneficial features of BlogEngine.Net, that I found it was popularly used by bloggers nowadays. I think BE has emerged to be one of the best blogging platform right now. I wish you good luck with your blogging experiences.

basketball shoes sale US

Thursday, March 11, 2010 6:47 AM

basketball shoes sale

You have a point. Very insightful. A nice different perspective

wholesale shoes US

Friday, March 12, 2010 12:06 AM

wholesale shoes

Your blog seems interesting.Regards,Kevin.

alibabashoes US

Friday, March 12, 2010 2:51 PM

alibabashoes

I was thinking of using BlogEngine but then I saw that most of the sites I looked either had comments full of spam or they had simply closed the comments altogether. I hope that you have been able to combat the spam because at the moment it is something that is making me stay away from BE.

Add comment


(Will show your Gravatar icon)  

  Country flag

[b][/b] - [i][/i] - [u][/u]- [quote][/quote]



Live preview

Friday, March 12, 2010 4:40 PM