Pages

Thursday 16 February 2012

Bindings in Silverlight - Creating Sample Data

One of the powerful features of Silverlight is the ability to bind information to controls. Not only data but also styles and templates can be bound to controls in XAML.
We will cover the Bindings in a mini series of posts.   After completing this series, you will find answers to questions such as
What is the syntax for binding?
To what controls can you bind?
Can you change the values / format of data that you are binding?
The structure of this mini-series will be as follows      
1)      One way Data Binding {Just getting the data from the source and displaying it  }
a)      Binding simple data to the Data Grid
b)      Binding user classes to data grid
c)       Binding Data Grid data to Textbox  -  Introduction to Converters
d)      Binding Data to list box
2)      Using Data Templates to present data
In this introductory post however, we will see various ways of fetching sample data for our binding. We will also see the various screens where you can do data binding easily using Visual Studio/Expression Blend.     
The simplest way to get data is to create your own data in the program. You can make use of the simple data types, or you can create your own classes and pass those objects individually, or you can make collections and pass them.
But you can also let Expression blend do that work for you.  Simply click a few buttons and generate as much sample data as you want.  In order to do this, first create a new project and go to the Data tab.

If you are unable to locate the Data tab, then please enable it from the Window context menu.

In your data tabb, you have the Add data Symbol (Shown like a Database icon with a + Symbol). When you click it, you get options from where to create data.

Choose the “New Sample Data” option, since we don’t have any existing data.

When you press OK, the sample data will be added to the Data tab.  You can see that a Sample data source, with a default collection is created.

If you observe this screen, you can notice several things.
1)      You can create as many sample sources as you like
2)      Each sample source can have as many collections as you like
3)      Properties are customizable
For example, when you click on the right symbol of a property, you get options to change parameters.

 Right now, it is a string.  But you can set it to various types, including image. For now, we will change the format of the string to Name

In your Xaml page, now drag a Data Grid.  You can also drag the collection on a Combo Box or list box. When you are dragging the collection, it will appear like this. 

Once you drop it, data will be bound and it will appear like this
       
If you will take a look at the XAML file, you will see auto generated bindings for you.

We will cover how to create such bindings for our own data and explore further in the Series. I hope you can create sample data now, for testing your bindings. We will be fetching most of our data from collections , either from a web service, or user defined Collections very shortly.

MVVM implementation in Expression Blend

The Model – View – View Model Pattern, also known as MVVM helps us create very scalable and efficient WPF/Silverlight applications that have some sort of Data access functionality. This is because of its clear separation of elements, just like the MVC Pattern.  
The User interface (UI) is separated from the Data and business logic, and put into a separate layer called the View.  There can be many views for an application, and any changes you make to your view do not affect your other layers.   This very property makes it easy for development teams to focus exclusively on design, or create several Views having different ways to access data. It also makes it convenient for skinning the UI.
Next in the pattern comes the Model.  This contains/provides the data classes necessary for the application. Your Model does not have any interaction with the View.  Its only task is to represent data from the database/external sources.  Since the View and Model are unaware of each other, you can have multiple models, which can be interchanged if necessary.  This makes it convenient to access data from various kinds of data sources, without the user not having to change the interface at all.
And finally, the most important part of this Pattern, the ViewModel.  The View model can respond to the changes in the UI through commands. The commands cause some methods to be fired, which change the properties of the view.  It can access data from the Model, which in turn is accessible to the View.
We will be building an application that does no data access for now.  Our focus will be on the View and the ViewModel.  So create a new Data Bound Silverlight Application in expression Blend.  I am using Blend 4.0.   Name the application as Silver MVVM, and press Ok.

This Silverlight Data bound Application template creates the default structure for your project, including Sample Data, a View Model, and a View.  Here the Sample Data acts as a Model.
The project structure that gets created is shown below.

The View contains all your interaction elements and is the visible UI.  The advantage of using the MVVM pattern is that the code behind file for the view, i.e. MainView.cs here, can be empty without event handlers or any code at all.
The default View contains a textbox and a button. On clicking the button, the text of the textbox is updated. We will be creating a rectangle and a button. Upon clicking the button, the color of the rectangle will change.  We will be modifying the existing code to accommodate the new controls. We will do the following steps while building this project.
1)      Create the new controls in the View
2)      Create the properties and a method in the View Model
3)      Binding the properties of the View model to the view in XAML

Step 1  -  Modifying the View


This is the default View.

Add the button and rectangle in View.  We don’t need to add a single line of code at all.

Step 2  -  Modifying the ViewModel


For editing the View Model, open the MainViewModel.cs, which is shown below.

Since we are trying to change the color of the rectangle, we will be using the Brush class present in System.Windows.media.  So add a reference to System.Windows.Media  

We are exposing a property called MyBrush, which will be bound to the Rectangle in the view.   So we first add that to the View Model.

We also need to write a method that will be called when the button is clicked.  We’ll call that method as ViewRectangleButton ().

Step 3  -  Changing the Bindings in the View XAML.

Open the XAML for the View.  You will find that there are default bindings for the existing button.

When you create 2 controls, the rectangle and the button, the following code will be added.



Change the code by Binding the Fill of the rectangle to MyBrush, and the MethodName to ViewRectangleButton.


T  That’s it.  You have successfully enabled the button click to change the Rectangle color.
           Before Click                                                        After Click


Additional Steps

If you want to create a new user control that also follows MVVM, you already have existing item templates for that.  Click on “Add New Item” in the Solution explorer, and you will be presented with various options.

Select the User Control with ViewModel.

It will create a View and a ViewModel, and your project structure will now look like this .

You can use the same steps to implement complex bindings and add new functionality using the MVVM pattern.