Data Binding

Data Binding is one of the principle features of Silverlight where elements can be bound to Data, which in this case will be a Collection of Data which can be Saved using IsolatedStorage.

www.cespage.com/silverlight/sl4tut22.html

Step 1

Start Microsoft Visual Web Developer 2010 Express, then Select File then New Project... Select "Visual Basic" then "Silverlight Application" from Templates, select a Location if you wish, then enter a name for the Project and then click OK, see below:

New Project

Step 2

New Silverlight Application window should appear, uncheck the box "Host the Silverlight Application in a new Web site" and then select the required Silverlight Version, see below:

New Silverlight Application

Step 3

A Blank Page named MainPage.xaml should then appear, see below:

MainPage.xaml

Step 4

Select Project then Add Reference... The "Add Reference" window should appear, select "System.XML.Linq" from the ".NET" List, see below:

Add System.XML.Linq Reference

Step 5

Add the Reference to "System.XML.Linq" by Clicking on OK
Select Project then "Add Class...", and select the "Class" Template if not already Selected, then change the "Name" to Music.vb , see below:

Music Class

Step 6

Add the new Class to the Project by Clicking on Add, then in the Code View for the Music.vb Class, above the "Public Class Music" line type the following:

Imports System.ComponentModel

See Below:

Music Class References

Step 7

While still in the Code View for the Music.vb Class, below the "Public Class Music" line type the following:

  Inherits INotifyPropertyChanged
Private _album As String
Private _artist As String
Private _released As String
Private _genre As String

Public Event PropertyChanged As PropertyChangedEventHandler _
    Implements INotifyPropertyChanged.PropertyChanged

See Below:

Music Class Declarations

Step 8

While still in the Code View for the Music Class, above the "End Class" for "Public Class Music", type the following Subs:

Private Sub NotifyPropertyChanged(ByVal PropertyName As String)
  RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(PropertyName))
End Sub

Public Sub New()
  _album = "Untitled"
End Sub

See Below:

Music Class Subs

Step 9

While still in the Code View for the Music Class, above the "End Class" for "Public Class Music", type the following Properties:

Public Property Album As String
  Get
    Return _album
  End Get
  Set(ByVal value As String)
    _album = value
    NotifyPropertyChanged("Album")
  End Set
End Property

Public Property Artist As String
  Get
    Return _artist
  End Get
  Set(ByVal value As String)
    _artist = value
    NotifyPropertyChanged("Artist")
  End Set
End Property

Public Property Released As String
  Get
    Return _released
  End Get
  Set(ByVal value As String)
    _released = value
    NotifyPropertyChanged("Released")
  End Set
End Property

Public Property Genre As String
  Get
    Return _genre
  End Get
  Set(ByVal value As String)
    _genre = value
    NotifyPropertyChanged("Genre")
  End Set
End Property

See Below:

Music Class Properties

Step 10

Return to the MainPage Designer View by selecting the "MainPage.xaml" Tab.
Then from the All Silverlight Controls section in the Toolbox select the Canvas control:

Canvas Control

Step 11

Draw a Canvas on the Page then in the XAML Pane above the "</Grid>" then change the "Canvas1" line to the following:

<Canvas Height="35" Width="400" VerticalAlignment="Top" HorizontalAlignment="Left" Name="Toolbar"></Canvas>

See below:

MainPage with Toolbar Canvas

Step 12

Then from the Common Silverlight Controls section in the Toolbox select the Button control:

Button Control

Step 13

Draw Three Buttons on the "Toolbar" Canvas by dragging the Buttons from the Toolbox onto the Canvas then in the XAML Pane inbetween the "<Canvas>" and "</Canvas>" tags change the "<Button>" lines to the following:

<Button Canvas.Left="6" Canvas.Top="6" Height="23" Width="75" Name="Add" Content="Add"/>
<Button Canvas.Left="87" Canvas.Top="6" Height="23" Width="75" Name="Remove" Content="Remove"/>
<Button Canvas.Left="168" Canvas.Top="6" Height="23" Width="75" Name="Save" Content="Save..."/> 

See below:

MainPage with Canvas and Buttons

Step 14

Then from the Common Silverlight Controls section in the Toolbox select the DataGrid control:

DataGrid Control

Step 15

Draw a DataGrid on the Page, below the Canvas with the Buttons, and in the XAML Pane above the "</Grid>" and below the "</Canvas>" change "DataGrid1" to the following:

<data:DataGrid Height="265" Width="400" Margin="0,35,0,0" VerticalAlignment="Top" HorizontalAlignment="Left" ItemsSource="{Binding}" Name="Data"/>

See below:

MainPage with Buttons and DataGrid

Step 16

Right Click on the Page or the entry for "MainPage.xaml" in Solution Explorer and choose the "View Code" option. In the Code View above the "Partial Public Class MainPage" line type the following:

Imports System.Collections.ObjectModel
Imports System.IO.IsolatedStorage
Imports System.Xml.Linq

See Below:

MainPage.xaml Imports

Step 17

While still in the Code View for MainPage.xaml, below the "Inherits UserControl" line type the following:

Public Filename As String = "Music.xml"
Public Property Collection As New ObservableCollection(Of Music)

See Below:

MainPage.xaml Declarations

Step 18

While still in the Code View, in the "Public Sub New()" constructor below the "InitializeComponent()" line type the following:

Using Storage As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication
  If Storage.FileExists(Filename) Then ' Open File
    Using OpenFile As New IsolatedStorageFileStream(Filename, IO.FileMode.Open, Storage)
      Dim _reader As XmlReader = XmlReader.Create(OpenFile)
      Dim _doc As XDocument = XDocument.Load(_reader)
      Collection.Clear()
      For Each Element As XElement In _doc.Root.<music>
        Collection.Add(New Music With {
          .Album = Element.<album>.Value,
          .Artist = Element.<artist>.Value,
          .Released = Element.<released>.Value,
          .Genre = Element.<genre>.Value})
      Next
    End Using
  Else ' New File
    Collection.Add(New Music With {
      .Album = "Tubular Bells",
      .Artist = "Mike Oldfield",
      .Released = "1973",
      .Genre = "Prog Rock"})
  End If
End Using
Data.DataContext = Collection

See Below:

MainPage.xaml Constructor

Step 19

Return to the Designer View by selecting the "MainPage.xaml" Tab, or Right Click on the Page or the Entry for "MainPage.xaml" in Solution Explorer and choose the "View Designer" option.
Double Click on the "Add" Button and type in the Add_Click Sub:

Collection.Add(New Music)

See Below:

Add Button Click Event

Step 20

Return to the Designer View by selecting the "MainPage.xaml" Tab, or Right Click on the Page or the Entry for "MainPage.xaml" in Solution Explorer and choose the "View Designer" option.
Double Click on the "Remove" Button and type in the Remove_Click Sub:

Collection.Remove(CType(Data.SelectedItem, Music))

See Below:

Remove Button Click Event

Step 21

Return to the Designer View by selecting the "MainPage.xaml" Tab, or Right Click on the Page or the Entry for "MainPage.xaml" in Solution Explorer and choose the "View Designer" option.
Double Click on the "Save..." Button Control and type in the Save_Click Sub:

Dim _doc As XDocument =
  <?xml version="1.0" encoding="utf-8"?>
  <collection>
    <%= From Item As Music In Collection Select
      <music>
        <album><%= Item.Album.Trim %></album>
        <artist><%= Item.Artist.Trim %></artist>
        <released><%= Item.Released.Trim %></released>
        <genre><%= Item.Genre.Trim %></genre>
      </music>
    %>
  </collection>
Using Storage As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication
  Using SaveFile As New IsolatedStorageFileStream(Filename, IO.FileMode.Create, Storage)
    _doc.Save(SaveFile)
  End Using
End Using

See Below:

Save Button Click Event

Step 22

Save the Project as you have now finished the Silverlight application. Select Debug then Start Debugging or click on Start Debugging:

Start Debugging

After you do, the following will appear in a new Web Browser window:

Application Running

Step 23

Click on "Add" then click on the "Untitled" Box to enter New Album Data, which can be entered into all of the Boxes and can then be Saved, see below:

Data Binding

Step 24

Close the Application and Browser window by clicking on the Close Button Close on the top right of the Application Window and Web Browser to Stop the application.

This was a simple Data Binding example, it uses LINQ to read the Data from IsolatedStorage - which is a feature of Silverlight, plus also Saves Data with this done using the inline-XML syntax supported in Visual Basic. This example could be used as the basis of any Data-based application, make it your own!