Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon

Data binding from Expression Blend 4 in Silverlight 4

Save for later
  • 7 min read
  • 13 May 2010

article-image

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:

data-binding-expression-blend-4-silverlight-4-img-0


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)
    {
    InitializeComponent();
    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);
    ownerDetailsEdit.Show();
    }

  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. Unlock access to the largest independent learning library in Tech for FREE!
    Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
    Renews at €18.99/month. Cancel anytime
  8. 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}" >
    </TextBlock>

  9. 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}" >
    </TextBlock>

  10. 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}" >
    </TextBox>


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:

data-binding-expression-blend-4-silverlight-4-img-1


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.
GetBindingExpression(TextBox.TextProperty);
expression.UpdateSource();

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.