Dear visitor, thanks for stopping by! If you want, you can follow all updates on via RSS. You can also follow me on Twitter or Facebook. More interesting posts from other Microsoft Regional Directors can be found at The Region.
Gill Cleeren     .net | C# | Microsoft | Programming | Vista | WinFX | WPF | XAML     July 11, 2006    

WPF not only stands for new fantastic tools for layout. There are also some very interesting new ways to implement databinding in your applications.
In this article, I’m going to show how you can easily build an RSS reader using the new databinding features in WPF.

How databinding works in WPF
In order not to go too fast, first, let me explain some basic concepts of databinding in WPF.

To keep data used in UI in sync with data in the datasource (for example a database), we can of course use properties. There is nothing wrong if you keep doing this under WPF.
However, WPF provides very handy binding features, that will make your life a lot easier!

We could bind the value of a textbox with the following code:
<TextBox Text="{Binding Path=Age}">

Databinding under WPF uses a Binding object. The above code declares a textbox in XAML, and assigns the text-property the value of a property named Age of an object that it is bound to. This is done using the Path property. The Path property refers to the property of the object we are binding too.

To know to which object we are binding, we have the DataContext property. In WPF, every FrameworkElement and also every FrameworkContentElement has a DataContext property. It is of type object, so we can bind to whatever we like.
The binding does however have some interesting behaviour: if no DataContext is specified on the object itself (like with our textbox), it goes up the tree in which the controls are nested. So if we add our textbox in a Grid, it will look if this Grid has a DataContext. If not, it goes up higher…
This is of course very useful if we have more than one object (say 5 textboxes) binding to the same object.

Let me show you how to declare an object to which we’ll bind in XAML code (this uses the new syntax, so to run this, you have to upgrade to beta 2 or higher!)

<Window x:Class="Snowball.Window2"
    Title="Snowball" Height="300" Width="300"
    <local:Person x:Key="Gill" Name="Gill Cleeren" Age="27"/>
    <Grid DataContext="{StaticResource Gill}">
      <TextBox Text="{Binding Path=Name}">

And in the code-behind:
namespace Snowball
    public class Person
        private string name;

        public string Name
            get { return name; }
            set { name = value; }
        private string age;

        public string Age
            get { return age; }
            set { age = value; }

        public Person()
        { }

What I have done here, is creating a Person object in XAML. For this to work, you have to provide a default constructor.
First, we have to wire the CLR namespace to be known in XAML: xmlns:local="clr-namespace:Snowball".
Now, we can use the tag “local” to refer to the namespace in which the Person class resides.
Using the following line, we instantiate a Person using XAML:
<local:Person x:Key="Gill" Name="Gill Cleeren" Age="27"/>

The result is a textbox showing my name:

Note that if you try this in Visual Studio at the time of writing, you get an error viewing the design view. Don’t worry, when running, it all works fine.

Binding XML data to a list
Most of the time, we bind data to a list: a dropdown, a grid… In this part, I’m going to bind an RSS feed from my website to a list.
To do this, we’ll need an XmlDataProvider.

Data can be accessed by using a Provider. Currently, 2 providers exist: the XmlDataProvider and the ObjectDataProvider.
An XmlDataProvider object must be declared within the resources, for example the resources of the grid:

        <XmlDataProvider x:Key="SnowballRSS" Source="" />

The x:Key assigns a name, which we can use in our code-behind.

We can now use this object as a datasource for a listbox, like this:

<ListBox ItemsSource="{Binding Source={StaticResource SnowballRSS}, XPath=//rss//channel//item }">

We provide a value for the ItemSource, being an instance of Binding. For this Binding instance, we provide the Source property. Since we’re dealing with a resource that is defined in the XAML itself, we again use StaticResource and as value, the name of the dataprovider. A second attribute is the XPath expression, to locate the value we want to show in the listbox.

This is the result:

What happens, is that the entire XML tag is being read into a listitem. This is not desired, so we have to provide some kind of formatting, to tell WPF exactly what we want to show in the items.
This can be accomplished using a datatemplate.

We provide an instance of DataTemplate to be used as value for the ItemTemplate property of the listbox. In this datatemplate, we can specify what to show as listitem.
In the following code, I’m telling to make each listitem consist of a TextBlock. The text to be shown is taken from the surrounding Listbox (remember searching for the data up in the controltree?). In the data it finds, which is an XML tag with subnodes, we can to take the title as the value for the item.

      <TextBlock Text="{Binding XPath=title}"></TextBlock>

When we now run this, we get the following:

Much better, isn’t it?!

In the next part, we’re going to make the application a little bit more complete, providing a click event for the listbox, and making sure that some fields are filled in, again using databinding.

Adding the detailsform
We’ll now change the program somewhat to make it display the details of the item selected in the listbox.

We’ll add a Grid to make it easy to display 3 rows and 2 columns with textblocks, labels and textboxes.
This can be done with the following code:

      <RowDefinition Height="30"></RowDefinition>
      <RowDefinition Height="30"></RowDefinition>
      <RowDefinition Height="*"></RowDefinition>
      <ColumnDefinition Width="0.2*"></ColumnDefinition>
      <ColumnDefinition Width="0.8*"></ColumnDefinition>
   <TextBlock Grid.Row="0" Grid.Column="0">Title</TextBlock>
   <Label Grid.Row="0" Grid.Column="1"></Label>
   <TextBlock Grid.Row="1" Grid.Column="0">Link:</TextBlock>
   <Label Grid.Row="1" Grid.Column="1" ></Label>
   <TextBlock Grid.Row="2" Grid.Column="0">Article</TextBlock>
   <TextBox Grid.Row="2" Grid.Column="1"></TextBox>

After adding the Grid, we’ll also have to change the rest of the markup a little. Take a look at the sample code provided with this article to see the rest of the layout.

We now want the detail-fields display more info on the selected item in the Listbox.  Therefore, the Grid containing these fields should have its DataContext set to the item selected in the list. We do this with the following code:

<Grid DataContext="{Binding ElementName=RSSList, Path=SelectedItem}" >

The element is the name of the listbox, the path is once again the property within the source to which we’ll be binding the grid (and thus the detail fields).

Now, every time we select an item in the listbox, the grid has its datacontext set to this selected item. The fields can now get details as follows:

<Label Grid.Row="0" Grid.Column="1" Content="{Binding XPath=title}"></Label>

<Label Grid.Row="1" Grid.Column="1" Content="{Binding XPath=link}">

<TextBox Grid.Row="2" Grid.Column="1" Text="{Binding XPath=description}"></TextBox>

The result should resemble the following:

Congratulations, you built your first databound application, using WPF databinding and a simple datatemplate!

In my next (large) article, we’ll be looking at the styling tools provided by WPF to make this application look TONS better!

RSS (45.32 KB)

kick it on
  Posted on: Tuesday, July 11, 2006 3:56:47 PM (Romance Daylight Time, UTC+02:00)   |   Comments [2] Tracked by:
"piu bollente ragazze anale fotti" (piu bollente ragazze anale fotti) [Trackback]
"phentermine online pharmacies" (phentermine online pharmacies) [Trackback]
"discount gas lanterns" (discount gas lanterns) [Trackback]
"culo pia bello" (culo pia bello) [Trackback]
"prittiest amatoriali merda" (prittiest amatoriali merda) [Trackback]
"king kong the movie" (king kong the movie) [Trackback]
"dieta dimagrante vegetariana" (dieta dimagrante vegetariana) [Trackback]
"orologeria milano" (orologeria milano) [Trackback]
"ice breaker" (ice breaker) [Trackback]
"offerta praga" (offerta praga) [Trackback]
"divertente tedesco orale fotti" (divertente tedesco orale fotti) [Trackback]
"Free Cum Shots" (Free Cum Shots) [Trackback]
"march 11%2c 2004" (march 11%2c 2004) [Trackback]
"wild panty porn" (wild panty porn) [Trackback]
"phone card" (phone card) [Trackback]
"wrestling shoes and apparel" (wrestling shoes and apparel) [Trackback]
"live adult amateur webcam" (live adult amateur webcam) [Trackback]
"columbus ohio commercial real estate" (columbus ohio commercial real estate) [Trackback]
"vendita roulotte" (vendita roulotte) [Trackback]
"amateur lesbian full video" (amateur lesbian full video) [Trackback]
"fertility rate" (fertility rate) [Trackback]
"masturbating womens" (masturbating womens) [Trackback]
"disneyland tickets" (disneyland tickets) [Trackback]
"self inflating mattress" (self inflating mattress) [Trackback]
"female ejaculation personal experiences" (female ejaculation personal experienc... [Trackback]
"cutie fighette sesso" (cutie fighette sesso) [Trackback]
"san francisco nose job" (san francisco nose job) [Trackback]

7/4/2015   5:20:50 AM
 Welcome to
Hello and welcome to!

My name is Gill Cleeren, I'm a Microsoft Regional Director and an MVP ASP.NET.
On, you'll find all kind news and articles on .net, ASP.NET, WPF, Silverlight and Microsoft in general.
More on me can be found on my about page.

Should you have any questions, don't hesitate to contact me by Send mail to the author(s) .

 Partner sites
 Most popular tags
.net (124) .net 3.0 (6) .net 3.5 (18) .NET 4 (18) .NET Show (1) (4) (53) AJAX (4) ASP.NET MVC (3) Atlas (12) Azure (2) Blend (2) Book (6) Book review (4) C# (43) Case studies (1) Chopsticks (3) Community (10) Community Day (16) Consoles (1) Database (1) DevDays09 (4) DotNetNuke (4) Efficiency (57) Enterprise Library (5) Events (62) Expression (7) Games (3) Hardware (9) Internet (18) IT (1) jQuery (1) LightSwitch (3) Links (11) LINQ (4) Mac (2) Metro (1) Microsoft (75) Mix 07 (6) Mix 08 (4) Mix 09 (1) Mix 11 (1) Movies (4) MVP (5) MVP Summit 2008 (3) mvvm (1) NDCOslo (1) Office 2007 (10) Other (8) PDC (22) PDC2008 (10) Personal (36) ppt (9) Programming (52) Programming tools (22) Regional Director (2) Silverlight (143) Silverlight Advent Calendar (24) sl4 (44) SL5 Data and Services Cookbook (2) Slide decks (13) Snowball (13) Software (20) Microsoft (25) Speaking (15) SQL Server (10) TechDays (13) TechEd (14) telerik (6) Telerik (6) TFS (1) Twitter (1) Vista (73) Vista Tricks (9) Visual (38) Visug (33) VS2010 (8) Wallpaper (2) WCF (2) Webcasts (9) Webinars (5) Windows (41) Windows 7 (5) Windows 8 (3) Windows Azure (2) Windows Mobile (3) Windows Phone 7 (2) WinFX (17) WinRT (2) WP7 (2) WPF (40) XAML (24)

 On this page
 This site
 Blogroll OPML

All content is property of Nothing on this site can be copied or published elsewhere, unless otherwise stated.

This site is made by Gill Cleeren.

Questions? Opinions? Send mail to the author(s) E-mail