SingingEels : Development Community & Resource

Login

Articles

  • ADO.NET (2)
  • ASP.NET (36)
  • LINQ (5)
  • Security (2)
  • Silverlight (3)
  • SQL (7)
  • Standards (5)
  • WCF (2)

Syndication

  • Articles RSS
  • Blogs RSS

Contribute

  • Our Authors List
  • Member Sign-Up
  • Suggestions Box

Silverlight DataBinding Basics

(Nov 22 2008 - 07:39:31 PM by Timothy Khouri) - [print article]

One of the most common uses of "Rich Interactive [web] Applications" is that of manipulating data. Silverlight enables developers to build powerful data-bound applications relatively easily. This article is designed to introduce and explain how to use data-binding in Silverlight applications. You can download the full demo project at the end of the article.

We're going to assume that we have a database with customer information. Our simple application will have the responsibility of displaying the list of customers to the user, and letting them edit their basic information (name and address). For the sake of keeping the demo simple, we are going to simply hard-code the list of "Person" objects in the Loaded event of our application.

What we will achieve by the end of this article is displaying the list of customers, showing the customer's address info when selected, and updating our list when a customer's name is updated.

If you are familiar with WPF, then this might seem like an extremely trivial task. The truth is, Silverlight2 doesn't support all of the functionality of WPF. Yes, it will still be relatively easy, but it won't be as simple as it would be in WPF.

Step One - Setting the ItemsSource

There are multiple ways that we can go about populating our ListBox with the customers. We could set the binding all in the XAML; we could iterate through our collection and "Add" to the "Items" collection; or we could set the "ItemsSource" property in the code behind. Because we are assuming that we just got the customers from the database (in the code behind), we're going to use option three: setting the ItemsSource property manually.

In order to be able to identify our ListBox in the code behind, we'll give it a Name of "PeopleList". Our XAML will now look something like this:

<ListBox Name="PeopleList" />

And our code behind will look something like this:

var people = GetPeopleFromDatabase();

this.PeopleList.ItemsSource = people;

This will work, but not to our liking. The problem here is that our ListBox will simply call "ToString()" on our Person objects, and that will make an ugly list that looks like this:

Silverlight list box not formatted

Step Two - Setting the ItemTemplate (or DisplayMemberPath)

To make our list display our customers in a more readable manner, we will change the way each item is displayed. For simple cases where we want to just show a single property (like 'FirstName'), we would just set the 'DisplayMemberPath' property. But in this case, we'll make our own ItemTemplate to bind the FirstName and the LastName with a space between the two. Here's the code:

<!-- Example of using DisplayMemberPath -->
<ListBox Name="PeopleList" DisplayMemberPath="FirstName" />

<!-- Example of creating your own ItemTemplate -->
<ListBox Name="PeopleList">
   <ListBox.ItemTemplate>
       <DataTemplate>
           <StackPanel Orientation="Horizontal">
               <TextBlock Text="{Binding FirstName}" />
               <TextBlock Text=" " />
               <TextBlock Text="{Binding LastName}" />
           </StackPanel>
       </DataTemplate>
   </ListBox.ItemTemplate>
</ListBox>

And here is what our list will look like now:

Silverlight list box formatted with a DisplayMemberPath

Step Three - Binding and the DataContext

Our Silverlight2 application has a list of customers displayed on the left, and some TextBoxes on the right for the purpose of editing the selected customer. But how can we wire up those TextBoxes to first display the current values, and secondly update them after editing? The answer is context - DataContext to be exact!

In WPF and WPF/E (Silverlight), the DataContext is a property that basically says "Any data that I'm binding to is a property on the data item either me, or my parent is set to." What this means is that if you have a TextBox inside of a StackPanel inside of a Grid... and you set the DataContext of that Grid to an instance of a Person object, then all child elements can get or set properties from that person instance.

To put this all together, we have five TextBoxes that are all inside of a Grid. And when we select a customer from our list, we are going to set the DataContext of that Grid to that customer. Here's our code:

void PeopleList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
   this.DetailsGrid.DataContext = this.PeopleList.SelectedItem;
}
<TextBox Text="{Binding FirstName, Mode=TwoWay}" />
<TextBox Text="{Binding LastName, Mode=TwoWay}" />
<TextBox Text="{Binding Address, Mode=TwoWay}" />
<TextBox Text="{Binding City, Mode=TwoWay}" />
<TextBox Text="{Binding State, Mode=TwoWay}" />
<TextBox Text="{Binding Zip, Mode=TwoWay}" />

And here's the end result:

Silverlight databinding application after selecting a person

This code above makes TwoWay data binding in Silverlight look a bit easier than it is. Really, with WPF you could just stop here. However, Silverlight runs on a lesser permission set (and has other restrictions such as the UI thread) that requires us to doctor up our "Person" class a bit.

You might think that the "FirstName" property of the Person class looks like this:

public string FirstName { get; set; }

But if we want Silverlight to be notified of the values changing in our model, then we have to implement the "INotifyPropertyChanged" interface and add a little code to our properties. Now, our FirstName property looks like this:

private string firstName;
public string FirstName
{
   get { return this.firstName; }
   set
   {
       this.firstName = value;
       this.NotifyPropertyChanged("FirstName");
   }
}

As a learning exercise, download the sample project at the end of this article and comment out the call to 'NotifyPropertyChanged'. Then, run the app and edit someone's first name. You'll notice that the ListBox will *NOT* update correctly to display the new name.

Step Four - Try it out!

Data binding in Silverlight enables web developers to create powerful data-centric applications. As technology blasts forward, the near future years of development in general will continue to grow in more and more powerful web based applications. The syntax of XAML and the framework of Silverlight may seem a bit foreign at first, but the more you play around with it, the more you understand it and love it. Here's the demo project for this article. Download it and check things out for yourself: SingingEels_SilverlightDataBinding.zip

You must be logged in to add comments. If you have not already done so, you can create an account here. If you already are a member, you first need to login before you can comment.

Developer / Architect / Author

People to Follow

Experts in the categories related to this article.

  • Bill Reiss
  • Wilco Bauwer

Related Blogs

These are the most recent blog posts related to this article.

  • Silverlight 2 Beta 2 - Image Source Bug With QueryString Parameters
  • Silverlight 2 Beta 1 - Online Game and the Pain it Caused
  • Silverlight Beta Has WCF, LINQ, Windows Controls!

Related Ads

SingingEels.com as of Jul 04 2009 - 10:03:17 AM - (0.0781375)