Silverlight Tutorial Part 5: Using the ListBox and DataBinding to Display List Data

This is part five of eight tutorials that walk through how to build a simple Digg client application using the Beta1 release of Silverlight 2.  These tutorials are intended to be read in-order, and help explain some of the core programming concepts of Silverlight.  Bookmark my Silverlight 2 Reference page for more of Silverlight posts and content. 

<Download Code> Click here to download a completed version of this Digg client sample. </Download Code>

Displaying our Digg Stories using the ListBox and DataBinding

Previously we've been using the DataGrid control to display our Digg stories.  This works great when we want to display the content in a column format.  For our Digg application, though, we probably want to tweak the appearance a little more and have it look less like a DataGrid of stories and more like a List of them.  The good news is that this easy - and it doesn't require us to change any of our application code to accomplish this.

We'll start by replacing our DataGrid control with a <ListBox> control.  We'll keep the control name the same as before ("StoriesList"):

 

When we run our application again and search for stories, the ListBox will display the following results:

You might be wondering - why is each item "DiggSample.DiggStory"?  The reason for this is because we are binding DiggStory objects to the ListBox (and the default behavior is to call ToString() on them).  If we want to display the "Title" property of the DiggStory object instead, we can set the "DisplayMemberPath" property on the ListBox:

When we do this the Title will be what is displayed in the ListBox:

If we want to show more than one value at a time, or customize the layout of each item more, we can override the ListBox control's ItemTemplate and supply a custom DataTemplate. Within this DataTemplate we can customize how each DiggStory object is displayed.

For example, we could display both the DiggStory Title and NumDiggs value using a DataTemplate like below.  

We can databind any public properties we want from our DiggStory object within the DataTemplate.  Notice above how we are using the {Binding PropertyName} syntax to accomplish this with the two TextBlock controls.

With the above DataTemplate in place, our ListBox will now display its items like below:

Let's then go one step further and change our DataTemplate to the one below.  This DataTemplate uses two StackPanels - one to stack row items horizontally, and one to stack some textblocks together vertically:

The above DataTemplate causes our ListBox to display items like the screen-shot below:

 

when we define the following Style rules in our App.xaml (note how we are using a LinearGradientBrush to get the nice yellow gradient background on the DiggPanel):

 

One important thing to notice about our ListBox - even though we have customized what the items in it look like, it still automatically provides support for hover and item selection semantics.  This is true both when using the mouse and when using the keyboard (up/down arrow keys, home/end, etc):

The ListBox also supports full flow resizing - and will provide automatic scrolling of our custom content when necessary (notice how the horizontal scroll bar appears as the window gets smaller):

Next Steps

We've now switched our data visualization to be List based, and cleaned up the content listing of it.

Let's now complete the last bits of the functionality behavior in the application - and implement a master/details workflow which allows end-users to drill into the specifics of a story when they select an article from the list.  To-do that let's jump to our next tutorial: Using User Controls to Implement Master/Detail Scenarios.

Published Friday, February 22, 2008 5:51 AM by ScottGu

Comments

# Scott Gu SilverLight 2 Tutorial Part 5

Friday, February 22, 2008 10:50 AM by DotNetKicks.com

You've been kicked (a good thing) - Trackback from DotNetKicks.com

# Scott Guthrie lève le voile sur Silverlight 2

Saturday, February 23, 2008 5:38 AM by Christophe Lauer, Blog Edition

A une semaine de l'ouverture de la conférence Mix08 de Las Vegas, Scott Guthrie - Corporate Vice President

# First Look at Silverlight 2

Saturday, February 23, 2008 4:49 PM by ScottGu's Blog

Last September we shipped Silverlight 1.0 for Mac and Windows , and announced our plans to deliver Silverlight

# re: Silverlight Tutorial Part 5: Using the ListBox and DataBinding to Display List Data

Sunday, February 24, 2008 4:52 PM by JONG DUK KIM(papasmf1)

Wow! It's Great! I wait longtime this product!!!

# MSDN Blog Postings &raquo; A better web is coming [Silverlight 2 is on the way!]

Pingback from  MSDN Blog Postings  &raquo; A better web is coming [Silverlight 2 is on the way!]

# Silverlight 2.0 Video Tutorials

Wednesday, March 05, 2008 8:57 PM by Dan Wahlin's WebLog

Silverlight 2.0 provides a new and exciting framework for building rich applications using C#, VB.NET

# Primer vistazo usando Expression Blend con Silverlight 2 &laquo; Thinking in .NET

Pingback from  Primer vistazo usando Expression Blend con Silverlight 2 &laquo; Thinking in .NET

# Excelentes Tutoriales para Silverlight 2 &laquo; Tecnologias Microsoft

Pingback from  Excelentes Tutoriales para Silverlight 2 &laquo; Tecnologias Microsoft

# re: Silverlight Tutorial Part 5: Using the ListBox and DataBinding to Display List Data

Friday, March 07, 2008 5:19 AM by Justin

I was having troubles displaying the thumbnails.  It looks like the XML returned by Digg places the Url in an attribute "src" under the "thumbnail" element.

I got around this by changing the assignment of the ThumbNail property of the DiggStory in the DisplayStories method as follows...

  ThumbNail = (string)story.Element("thumbnail").Attribute("src")

# re: Silverlight Tutorial Part 5: Using the ListBox and DataBinding to Display List Data

Friday, March 07, 2008 10:13 AM by Ramiro Berrelleza

Is it possible to configure the ListBox so it will display the elements horizontally instead of vertically? It is possible in WPF, but is it possible in Silverlight's ListBox?

# re: Silverlight Tutorial Part 5: Using the ListBox and DataBinding to Display List Data

Friday, March 07, 2008 4:44 PM by Thia

I had it working until now. The data was coming up (although the images werent), but everything else was.

Now - when I put in a subject and click Search, the application turns white.

What did I do? LOL

The Digg URL I am using is:

services.digg.com/.../topic{0}?count=10&appkey=http%3A%2F%2Fwww.example.com%2Fapplication

# Silverlight チュートリアル パート 5: ListBoxの使用と一覧データの表示へのデータバインディング

Sunday, March 09, 2008 4:56 AM by Chica's Blog

Silverlight チュートリアル パート 5: ListBoxの使用と一覧データの表示へのデータバインディング

# re: Silverlight Tutorial Part 5: Using the ListBox and DataBinding to Display List Data

Monday, March 10, 2008 9:48 AM by zoltan.arvai

Thia:

The images are not displaying because the linq query on the picture has a bug.

It should be: ThumbNail = (string)story.Element("thumbnail").Attribute("src")

Well i use scott's url and it works fine :)

# re: Silverlight Tutorial Part 5: Using the ListBox and DataBinding to Display List Data

Monday, March 10, 2008 2:31 PM by Joey

I run the app, type in a seach term, click "Search", and I get no results. If I set a breakpoint I can see that "e.Error" in the "DiggService_DownloadStoriesCompleted" function is NOT null. When I hover the mouse over it all I can see is "Download Failure". Below is the DiggURL as copied from source and pasted into here...

services.digg.com/.../topic{0}?count=20&appkey=http%3A%2F%2Fsomesite.com

...What is causing this, and how can I fix it?

# Primer vistazo a Silverlight 2 &laquo; Thinking in .NET

Tuesday, March 11, 2008 4:40 AM by Primer vistazo a Silverlight 2 « Thinking in .NET

Pingback from  Primer vistazo a Silverlight 2 &laquo; Thinking in .NET

# re: Silverlight Tutorial Part 5: Using the ListBox and DataBinding to Display List Data

Friday, March 14, 2008 10:31 AM by Greg McCarty

FYI - when my 'NumDiggs' textblock references a static resource, I get no display from a successful query.  When I manually enter the 4 style elements in the textblock, it works.

# re: Silverlight Tutorial Part 5: Using the ListBox and DataBinding to Display List Data

Sunday, March 16, 2008 9:30 PM by Nish

Joey,

Try a topic that exists like Apple

I tried 'asp' and it did the same thing

# Ressources développeur pour Silverlight 2

Monday, March 17, 2008 6:05 PM by Pierre Lagarde, Blog

Depuis la mise a disponibilité de Silverlight 2 au Mix08 il y a eu beaucoup d'articles, de blogs sur

# Tutorial Silverlight. Parte 5: ListBox y DataBinding para listar datos. &laquo; Thinking in .NET

Pingback from  Tutorial Silverlight. Parte 5: ListBox y DataBinding para listar datos. &laquo; Thinking in .NET

# re: Silverlight Tutorial Part 5: Using the ListBox and DataBinding to Display List Data

Friday, March 21, 2008 8:22 PM by Juan María

hi all:

you can read this post in spanish here:

thinkingindotnet.wordpress.com/.../tutorial-silverlight-parte-5-listbox-y-databinding-para-listar-datos

# Silverlight 2, les contrôles et l'écosystème

Saturday, March 29, 2008 9:36 AM by ASP.NET Français Blogs

Incontestablement, les contr&#244;les graphiques sont une des nouveaut&#233;s de Silverlight 2 qui &#233;taient

# Creating a Silverlight Chinese-English Dictionary Program Part 3 of 3: Silverlight 2 Beta 1

Thursday, April 17, 2008 8:44 PM by Daniel Lesser's Blog

At present, Microsoft’s Expression Blend (using the March CTP 2.5) is the best way to graphically manipulate