Data binding from Expression Blend 4 in Silverlight 4

Using the different modes of data binding to allow persisting data

Until now, the data has flowed from the source to the target (the UI controls). However, it can also flow in the opposite direction, that is, from the target towards the source. This way, not only can data binding help us in displaying data, but also in persisting data.

The direction of the flow of data in a data binding scenario is controlled by the Mode property of the Binding. In this recipe, we'll look at an example that uses all the Mode options and in one go, we'll push the data that we enter ourselves to the source.

Getting ready

This recipe builds on the code that was created in the previous recipes, so if you're following along, you can keep using that codebase. You can also follow this recipe from the provided start solution. It can be found in the Chapter02/SilverlightBanking_Binding_ Modes_Starter folder in the code bundle that is available on the Packt website. The Chapter02/SilverlightBanking_Binding_Modes_Completed folder contains the finished application of this recipe.

How to do it...

In this recipe, we'll build the "edit details" window of the Owner class. On this window, part of the data is editable, while some isn't. The editable data will be bound using a TwoWay binding, whereas the non-editable data is bound using a OneTime binding. The Current balance of the account is also shown—which uses the automatic synchronization—based on the INotifyPropertyChanged interface implementation. This is achieved using OneWay binding. The following is a screenshot of the details screen:

Let's go through the required steps to work with the different binding modes:

  1. Add a new Silverlight child window called OwnerDetailsEdit.xaml to the Silverlight project.
  2. In the code-behind of this window, change the default constructor—so that it accepts an instance of the Owner class—as shown in the following code:
    private Owner owner;
    public OwnerDetailsEdit(Owner owner)
    this.owner = owner;
  3. In MainPage.xaml, add a Click event on the OwnerDetailsEditButton:
    <Button x:Name="OwnerDetailsEditButton"
    Click="OwnerDetailsEditButton_Click" >
  4. In the event handler, add the following code, which will create a new instance of the OwnerDetailsEdit window, passing in the created Owner instance:
    private void OwnerDetailsEditButton_Click(object sender,
    RoutedEventArgs e)
    OwnerDetailsEdit ownerDetailsEdit = new OwnerDetailsEdit(owner);
  5. The XAML of the OwnerDetailsEdit is pretty simple. Take a look at the completed solution (Chapter02/SilverlightBanking_Binding_Modes_Completed)for a complete listing. Don't forget to set the passed Owner instance as the DataContext for the OwnerDetailsGrid. This is shown in the following code:
    OwnerDetailsGrid.DataContext = owner;
  6. For the OneWay and TwoWay bindings to work, the object to which we are binding should be an instance of a class that implements the INotifyPropertyChanged interface. In our case, we are binding an Owner instance. This instance implements the interface correctly. The following code illustrates this:
    public class Owner : INotifyPropertyChanged
    public event PropertyChangedEventHandler PropertyChanged;
  7. Some of the data may not be updated on this screen and it will never change. For this type of binding, the Mode can be set to OneTime. This is the case for the OwnerId field. The users should neither be able to change their ID nor should the value of this field change in the background, thereby requiring an update in the UI. The following is the XAML code for this binding:
    <TextBlock x:Name="OwnerIdValueTextBlock"
    Text="{Binding OwnerId, Mode=OneTime}" >
  8. The CurrentBalance TextBlock at the bottom does not need to be editable by the user (allowing a user to change his or her account balance might not be benefi cial for the bank), but it does need to change when the source changes. This is the automatic synchronization working for us and it is achieved by setting the Binding to Mode=OneWay. This is shown in the following code:
    <TextBlock x:Name="CurrentBalanceValueTextBlock"
    Text="{Binding CurrentBalance, Mode=OneWay}" >
  9. The final option for the Mode property is TwoWay. TwoWay bindings allow us to persist data by pushing data from the UI control to the source object. In this case, all other fields can be updated by the user. When we enter a new value, the bound Owner instance is changed. TwoWay bindings are illustrated using the following code:
    <TextBox x:Name="FirstNameValueTextBlock"
    Text="{Binding FirstName, Mode=TwoWay}" >

We've applied all the different binding modes at this point. Notice that when you change the values in the pop-up window, the details on the left of the screen are also updated. This is because all controls are in the background bound to the same source object as shown in the following screenshot:

How it works...

When we looked at the basics of data binding, we saw that a binding always occurs between a source and a target. The first one is normally an in-memory object, but it can also be a UI control. The second one will always be a UI control.

Normally, data flows from source to target. However, using the Mode property, we have the option to control this.

A OneTime binding should be the default for data that does not change when displayed to the user. When using this mode, the data flows from source to target. The target receives the value initially during loading and the data displayed in the target will never change. Quite logically, even if a OneTime binding is used for a TextBox, changes done to the data by the user will not flow back to the source. IDs are a good example of using OneTime bindings. Also, when building a catalogue application, OneTime bindings can be used, as we won't change the price of the items that are displayed to the user (or should we...?).

We should use a OneWay binding for binding scenarios in which we want an up-to-date display of data. Data will flow from source to target here also, but every change in the values of the source properties will propagate to a change of the displayed values. Think of a stock market application where updates are happening every second. We need to push the updates to the UI of the application.

The TwoWay bindings can help in persisting data. The data can now flow from source to target, and vice versa. Initially, the values of the source properties will be loaded in the properties of the controls. When we interact with these values (type in a textbox, drag a slider, and so on), these updates are pushed back to the source object. If needed, conversions can be done in both directions.

There is one important requirement for the OneWay and TwoWay bindings. If we want to display up-to-date values, then the INotifyPropertyChanged interface should be implemented. The OneTime and OneWay bindings would have the same effect, even if this interface is not implemented on the source. The TwoWay bindings would still send the updated values if the interface was not implemented; however, they wouldn't notify about the changed values. It can be considered as a good practice to implement the interface, unless there is no chance that the updates of the data would be displayed somewhere in the application. The overhead created by the implementation is minimal.

There's more...

Another option in the binding is the UpdateSourceTrigger. It allows us to specify when a TwoWay binding will push the data to the source. By default, this is determined by the control. For a TextBox, this is done on the LostFocus event; and for most other controls, it's done on the PropertyChanged event.

The value can also be set to Explicit. This means that we can manually trigger the update of the source.

BindingExpression expression = this.FirstNameValueTextBlock.

See also

Changing the values that flow between source and target can be done using converters.

Data binding from Expression Blend 4

While creating data bindings is probably a task mainly reserved for the developer(s) in the team, Blend 4—the design tool for Silverlight applications—also has strong support for creating and using bindings.

In this recipe, we'll build a small data-driven application that uses data binding. We won't manually create the data binding expressions; we'll use Blend 4 for this task.

How to do it...

For this recipe, we'll create a small application from scratch that allows us to edit the details of a bank account owner. In order to achieve this, carry out the following steps:

  1. We'll need to open Blend 4 and go to File | New Project.... In the New Project dialog box, select Silverlight 4 Application + Website. Name the project SilverlightOwnerEdit and click on the OK button. Blend will now create a Silverlight application and a hosting website.
  2. We'll start by adding a new class called Owner. Right-click on the Silverlight project and select Add New Item.... In the dialog box that appears, select the Class template and click on the OK button. The following is the code for the Owner class and it can be edited inside Blend 4:
    public class Owner
    public string Name {get; set;}
    public int CurrentBalance {get;set;}
    public DateTime LastActivityDate {get;set;}
  3. In the code-behind of MainPage.xaml, create an instance of the Owner class and set it as the DataContext for the LayoutRoot of the page.
    public partial class MainPage : UserControl
    public Owner owner;
    public MainPage()
    // Required to initialize variables
    owner = new Owner()
    Name="Gill Cleeren",
    Chapter 2
    LayoutRoot.DataContext = owner;
  4. Build the solution, so that the Owner class is known to Blend and it can use the class in its dialog boxes.
  5. Now, in the designer, add a Grid containing three TextBlock and three TextBox controls as shown in the following screenshot:

  6. We're now ready to add the data binding functionality. Select the first TextBox and in the Properties window, search for the Text property. Instead of typing a value, click on the small square for the Advanced property options next to the text fi eld. Select Data Binding... in the menu. The following screenshot shows how to access this option:

  7. In the dialog box that appears, we can now couple the Name property of the Owner type to the Text property of the TextBox. Under the Explicit Data Context tab, mark the Use a custom path expression checkbox and enter Name as the value. Click on the down arrow so that the advanced properties are expanded and mark TwoWay as the Binding direction. The other properties are similar as shown in the following screenshot:

How it works...

Let's look at the resulting XAML code for a moment. Blend created the bindings for us automatically taking into account the required options such as Mode=TwoWay. This is shown in the following code:

<TextBox Grid.Column="1"
Text="{Binding Name, Mode=TwoWay,
<TextBox Grid.Column="1"
Text="{Binding LastActivityDate, Mode=TwoWay,
<TextBox Grid.Column="1"
Text="{Binding CurrentBalance, Mode=TwoWay,

When we have to create many bindings, it's often easier to do so through these dialog boxes than typing them manually in Visual Studio.

Using Expression Blend 4 for sample data generation

Expression Blend 4 contains a feature that is capable of generating the sample data while developing an application. It visualizes the data on which we are working and provides us with an easier way to create an interface for a data-driven application. This feature was added to Blend in version 3.

How to do it...

In this recipe, we'll build a small management screen for the usage of the bank employees. It will show an overview of the bank account owners. We wouldn't want to waste time with the creation of (sample) data, so we'll hand over this task to Blend. The following are the steps we need to follow for the creation of this data:

  1. Open Blend 4 and go to File | New Project.... In the dialog box that appears, select Silverlight 4 Application + Website. Name the project as SilverlightBankingManagement and click on the OK button. Blend will now create a Silverlight application and a hosting website.
  2. With MainPage.xaml open in either the Design View or the Split View, go to the Data window. In this window, click on the Add sample data source icon and select Defi ne New Sample Data… as shown in the following screenshot:

  3. In the Define New Sample Data dialog box that appears, specify the Data source name as OwnerDataSource. We have the option to either embed this data source in the usercontrol (This document) or make it available for the entire project (Project). Select the latter option by selecting the Project radio button and clicking on the OK button.
    The last option in this window—Enable sample data when application is running— allows us to switch off the sample data while running the compiled application. If we leave the checkbox checked, then the sample data will be used for the design time as well as the runtime. We'll keep this option enabled.
    Blend will now generate the data source for us. The result is shown in the following screenshot:

  4. By default, a Collection is created and it contains items with two properties. Each property has a type. Start by adding two more properties by clicking on the + sign next to the Collection and select the Add simple property option.
    Rename Property1 to Name. Now, change the type options by clicking on the Change property type icon and selecting Name as the format. The other properties are similar and are shown in the following screenshot:

  5. For the Image type, we can select a folder that contains images. Blend will then copy these images to the SampleData subfolder inside the project.
  6. We're now ready to use the sample data—for example—in a master-detail scenario. A ListBox will contain all the Owner data from which we can select an instance. The details are shown in a Grid using some TextBlock controls. Make sure that the Data window is set to List Mode and drag the collection on to the design surface. This will trigger the creation of a listbox in which the items are formatted, so we can see the details.
  7. Now, to view the details, we have to set the Data window to the Details Mode. Then, instead of dragging the collection, we select the properties that we want to see in the detail view and drag those onto the design surface. The result should be similar to the following screenshot:

Thus, Blend created all the data binding code in XAML as well as the sample data. For each different type, it generated different values.


In this article, we discussed about:

  • Using the different modes of data binding to allow persisting data
  • Data binding from Expression Blend 4
  • Using Expression Blend 4 for sample data generation

If you have read this article you may be interested to view :

You've been reading an excerpt of:

Microsoft Silverlight 4 Data and Services Cookbook

Explore Title