Channels ▼
RSS

Web Development

Silverlight 2 Data Binding


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.


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.
 
Dr. Dobb's TV