Silverlight 2 Data Binding

Handling data once it is in memory


June 02, 2008
URL:http://www.drdobbs.com/web-development/silverlight-2-data-binding/208401405

Chad Campbell is a Microsoft MVP and solutions architect. Michael Schwarz is a software architect, a three-time Microsoft MVP, and a contributor to the Ajax.NET Professional library. Chad and Michael are the authors of Silverlight 2 In Action, on which this article is based. Courtesy Manning Publications. All rights reserved.


Data binding is a powerful way to create a connection between your UI and a source of data. This simple technique can be used to create a clean separation between your user interface and its underlying data. This segregation makes it easier to maintain an application down the road. In addition, this approach promotes fewer round trips to the server. Because of this, it can be argued that data binding can help you increase the performance of your application. Regardless of the reason, you can use data binding in your application by creating an instance of the Binding class.

The Binding class is used to define a connection between a CLR object and a UI component. This connection is defined by three essential components. These elements are the source of the data (the CLR object), the binding mode, and the target for the data (the UI component). These three items are part of a conceptual model that explains binding. This model is shown in Figure 1.

Figure 1: A conceptual view of data binding. This illustration uses the situation of binding the current time of day to a TextBox.

Figure 1 shows a high-level overview of how a data binding looks. This conceptual binding sets the Text property of a TextBox to the current TimeOfDay. In order to actually create a binding like this though, you must use one of two available binding syntaxes. These syntaxes require you to define both the source and the target of a binding. However, each approach is appropriate at a different time. Once you have decided which syntax is appropriate for your situation, you must decide how data can pass between the source and the target. This is the responsibility of the BindingMode.

Mastering the Binding Syntax

Silverlight gives you the ability to create a Binding using two different approaches. The first approach allows you to dynamically create a binding at runtime. The other option gives you the opportunity to specify a binding at design-time. Either way, the scenario from Figure 1 will be used to show both approaches.

Binding at Runtime

Binding to a data source at runtime is a common approach used in event-driven application development. For instance, you may decide to display a list of basketball games based on a date selected by a user. Or, you may decide to show the current time when an application is loaded. Either way, creating a Binding at runtime follows a common pattern which is shown in Listinge One.

<TextBox x:Name="myTextBox" />                   #1
  DateTime currentTime = DateTime.Now;                 #2
  Binding binding = new Binding("TimeOfDay");          #3
  binding.Source = currentTime;                        #3
  binding.Mode = BindingMode.OneWay;                   #3
  myTextBox.SetBinding(TextBox.TextProperty, binding); #3
Listing One: Adding a Binding to a TextBox from C#.

Listing One shows how to bind the value of a CLR property, to a UI element, at runtime. This snippet binds the current time of day to the TextBox that was created in XAML (#1). This was accomplished by first retrieving the DateTime object that represents the current moment in time (#2). This object was then bound to the UI element (the TextBox) in just four lines of code (#3). These four lines of code basically specify the source, the binding mode, and the target of a binding.

The source of a binding is made up of two co-dependent items. These items specify which property of a CLR object to bind to. The name of the property to bind to is set when you create a Binding instance through the constructor. This constructor takes a single string parameter which represents the name of the property to bind to. This property belongs to a CLR object which must be associated with a Binding through the Source property. Once this has happened, the source of the binding is officially set. You can then choose a BindingMode. But, once the source and binding mode have been set, you need to turn your focus to the target.

The target element of a binding will always derive from the FrameworkElement class. Because of this, virtually every visual element in Silverlight can be a target. This is true because the FrameworkElement class exposes a method called SetBinding. This method associates a target property, which must be a dependency property, with a Binding instance. After this method is called, the source will be bound to the target.

Occasionally though, there may be times when you want to unbind a data source. Fortunately, data binding can be halted by manually setting the target property of a binding. As an example, take a look at Listing Two.

myTextBox.Text = "Binding Removed";
Listing Two: Removing a Binding from a TextBox in C#.

Listing Two shows how easy it is to remove a binding after it has been set. This feature is only available at runtime simply because that is the only time it makes sense. Either way, using a Binding at runtime is a powerful option. Perhaps just as equally powerful though, is the ability to create a Binding at design-time.

Binding at Design-Time

Binding to a data source at design-time is a common feature in declarative markup languages such as XAML. You have probably seen the power of this data binding approach if you have used ASP.NET or WPF. If you haven't, don't worry. In essence, this approach allows you to keep your code separate from its presentation. This lets you take advantage of the developer/designer workflow available within Silverlight. Alternatively though, it just helps to keep your code clean and maintainable. To show how a binding in XAML can help clean up your code, look at Listing Three.

<TextBox x:Name="myTextBox" Text="{Binding TimeOfDay, Mode=OneWay}" /> #1
  DateTime currentTime = DateTime.Now;
  myTextBox.DataContext = currentTime; #2
Listing Three: Binding a property to a TextBox in XAML.

Listing Three shows how to create a binding at design-time. This binding is associated with a target through the use of a special syntax that uses curly braces ({}). These curly braces, along with the word Binding, inform a property that a data source will be bound to it (#1). This data source will be a CLR object that has some property to retrieve data from and possibly send data to. This property is identified within the curly braces after the word Binding (in Listing Three it's TimeOfDay). The other properties associated with the binding are set using a propertyName=propertyValue syntax (i.e., Mode=OneWay). However, the process of actually setting the data source must be done in code.

When creating a data binding in XAML, the data source must be set in procedural code. This code is responsible for setting the context in which a data source can be used. This context is set through the appropriately named DataContext property. For now though, just know that this is how a CLR object can be bound to a FrameworkElement.

Binding at design-time is a valuable option when it comes to working with data. In the same way, binding at runtime can also be a worthy choice. Regardless of where you define the binding, both approaches define a bridge between a source and a target. Significantly, data can flow in multiple directions across this bridge. In order to control the direction of that flow, you must learn about the various binding modes.

Choosing a Binding Mode

The Binding class gives you the ability to determine how data can flow between the source and the target. This flow can be controlled by setting the Mode property of a Binding instance. This property represents one of the three options available in the BindingMode enumerator. This enumerator exposes the OneTime, OneWay, and TwoWay options.

OneTime

The OneTime binding mode sets the target property to the source property when a binding is initially made. When this BindingMode is used, any changes to the data source will not be automatically sent to the target. Instead, the target will only be set when the source is initialized as shown in Figure 2.

Figure 2: A conceptual view of OneTime binding to a data source.

Figure 2 shows the simplistic binding nature of the OneTime BindingMode. As you can imagine, this BindingMode is appropriate in situations where you only care about the initial value of a property. For instance, you may want to display the "creation date" of a database record. Because this value should not change, the OneTime BindingMode is a great choice. However, for property values that will change, like the date/time that a database record was last modified, you may want to use the OneWay binding option.

OneWay

The OneWay BindingMode is the default option used when you create a Binding. This option gives you the ability to automatically receive changes from a source property. This means that whenever the binding source property changes, the target property will automatically change. However, the source property will not change if the target is altered. Either way, this change process is shown in Figure 3.

Figure 3: A conceptual view of OneWay binding to a data source.

Figure 3 shows how the OneWay BindingMode works at a high level. Alternatively, you may think of the speedometer in your car as OneWay binding from your gas pedal. Essentially, when you press or release your foot from the gas pedal, the speedometer changes. However, if you somehow changed the value of the speedometer itself, your gas pedal would not change. This inability to send a change from the target back to the source shows how OneWay binding works. For situations where you do want to send changes in the target back to the source, you can use the TwoWay option.

TwoWay

TwoWay binding enables two properties that are bound to each other, to change each other. At first glance, this may sound recursive, however it's not. Essentially a TwoWay binding changes the target when the source changes. On the other hand, if the target changes, the source will be updated. This can be seen in Figure 4.

Figure 4: A conceptual view of TwoWay binding to a data source.

Figure 4 shows a conceptual view of TwoWay binding. This binding approach is useful for web-based forms using Silverlight. The reason why is because forms generally allow users to add, as well as edit, data. This process of editing pre-existing data practically begs for TwoWay binding.

The TwoWay BindingMode is one of the options available to control the flow of your data. The other alternatives are available through the OneWay and OneTime options. Collectively, these options are an important part of setting up a binding. However, after the target and binding mode have been selected, you need to choose an appropriate source.

Terms of Service | Privacy Statement | Copyright © 2024 UBM Tech, All rights reserved.