Overview of Databinding in Silverlight

Posted by Corey on October 7, 2008 at 1:29 pm.

The goal the below code is to bind data using XAML.  So, for the example I used MLB Pitching stats for 2008, created a Pitcher object, then a PitcherCollection objet, and finally used XAML to define an instance of the PitcherCollection.  The result is the Page.xaml.cs does not have any code in it, but a list box is fully bound to a data source. 

  1. The data source.  This is a sample of the XML used.
  2. <Pitchers>
    
        <Pitcher>
    
            <Name>Johan Santana</Name>
    
            <Wins>16</Wins>
    
            <ERA>2.53</ERA>
    
        </Pitcher>
    
        <Pitcher>
    
            <Name>Cliff Lee</Name>
    
            <Wins>22</Wins>
    
            <ERA>2.54</ERA>
    
        </Pitcher>
  3. Next create two classes; the Pitcher and PitcherCollection.  Pitcher uses the interface INotifyPropertyChanged and PitcherCollection inherits ObservableCollection<Pitcher>

    using System.ComponentModel;
    
    
    
    namespace DataBindingExample.Data
    
    {
    
        public class Pitcher : INotifyPropertyChanged
    
        {
    
    
    
            #region INotifyPropertyChanged Members
    
    
    
            public event PropertyChangedEventHandler PropertyChanged;
    
    
    
            #endregion
    
    
    
            private void OnPropertyChanged(string propertyName)
    
            {
    
                if (PropertyChanged != null)
    
                {
    
                    PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    
                }
    
            }
    
    
    
            public string Name
    
            {
    
                get { return name; }
    
                set {
    
                    name = value;
    
                    OnPropertyChanged("name");
    
                }
    
            }
    
            private string name;
    
    
    
            public double ERA
    
            {
    
                get { return era; }
    
                set {
    
                    era = value;
    
                    OnPropertyChanged("era");
    
                }
    
            }
    
            private double era;
    
    
    
            public int Strikeouts
    
            {
    
                get { return srikeouts; }
    
                set {
    
                    srikeouts = value;
    
                    OnPropertyChanged("srikeouts");
    
                }
    
            }
    
            private int srikeouts;
    
    
    
            public int Wins
    
            {
    
                get { return wins; }
    
                set {
    
                    wins = value;
    
                    OnPropertyChanged("wins");
    
                }
    
            }
    
            private int wins;
    
    
    
    
    
        }
    
    }
    
    
    

    using System.Collections.ObjectModel;
    
    using System.Xml.Linq;
    
    using System.Linq;
    
    using System.Collections.Generic;
    
    
    
    
    
    namespace DataBindingExample.Data
    
    {
    
        public class PitchersCollection : ObservableCollection<Pitcher>
    
        {
    
            public PitchersCollection()
    
            {
    
                Load();
    
            }
    
    
    
            public void Load()
    
            {
    
                XDocument doc = XDocument.Load(@"Data/Pitchers.xml");
    
    
    
                var q = from p in doc.Descendants("Pitcher")
    
                        select new Pitcher
    
                        {
    
                            Name = (string)p.Element("Name"),
    
                            ERA = (double)p.Element("ERA"),
    
                            Wins = (int)p.Element("Wins"),
    
                            Strikeouts = 5
    
                        };
    
    
    
                if (q != null)
    
                {
    
                    // Add items to this collection
    
                    foreach (var item in q)
    
                    {
    
                        this.Add(item);
    
                    }
    
                }
    
            }
    
        }
    
    }
    
    
    
  4. Add the data source to the UserControl.Resources section of your XAML and add a ListBox control refrencing the object.
  5. <UserControl x:Class="DataBindingExample.Page"
    
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    
        xmlns:data="clr-namespace:DataBindingExample.Data"
    
        Width="400" Height="300">
    
    
    
        <UserControl.Resources>
    
            <data:PitchersCollection x:Key="PitchersCollection" />
    
        </UserControl.Resources>
    
    
    
        <Grid x:Name="LayoutRoot" Background="White">
    
            <!--<ListBox ItemsSource="{Binding Source={StaticResource PitchersCollection}, Mode=OneWay}"
    
                    DisplayMemberPath="Name">-->
    
            <ListBox ItemsSource="{Binding Source={StaticResource PitchersCollection}, Mode=OneWay}">
    
                <ListBox.ItemTemplate>
    
                    <DataTemplate>
    
                        <Grid>
    
                            <Grid.ColumnDefinitions>
    
                                <ColumnDefinition Width="150" />
    
                                <ColumnDefinition Width="*" />
    
                                <ColumnDefinition Width="*" />
    
                            </Grid.ColumnDefinitions>
    
                            <TextBlock Text="{Binding Path=Name, Mode=OneWay}" Grid.Column="0" />
    
                            <TextBlock Text="{Binding Path=Wins, Mode=OneWay}" Grid.Column="1" Margin="0,0,20,0" />
    
                            <TextBlock Text="{Binding Path=ERA, Mode=OneWay}" Grid.Column="2" />
    
                        </Grid>
    
                    </DataTemplate>
    
                </ListBox.ItemTemplate>
    
            </ListBox>
    
        </Grid>
    
    </UserControl>
    
    
    
  6. The resulting application:

    image

Resources:

Scott Guthrie’s Silverlight 2 introduction blog post.  Used this for the ListBox - http://weblogs.asp.net/scottgu/pages/silverlight-tutorial-part-5-using-the-listbox-and-databinding-to-display-list-data.aspx

LINQ to Objects - http://www.hookedonlinq.com/LINQtoObjects5MinuteOverview.ashx

3 Responses to “Overview of Databinding in Silverlight”

Leave a Reply