Runtime Binding

Although you can bind Silverlight 2 applications using the XAML syntax shown in the previous examples, you also can set up binding entirely through .NET code. This technique allows a developer to change the bindings at runtime, which is good in situations when the source or property may not be known at design time. For example, a TextBox might need to be bound to a different property based on business logic that is executed at runtime. In this case, the bindings could be created conditionally based on the logic.

You can create the bindings using the System.Windows.Data namespace and an instance of the Binding class. The Binding class is the same class that you can create through the markup extensions shown in Example 2-6. Therefore, it has the same five properties, as shown in the IntelliSense menu in Figure 2-4.

Binding class members

Figure 2-4. Binding class members

Creating Runtime Bindings

A runtime binding first requires that a binding be created and a target property specified. Then the binding must either use the inherited DataContext or indicate a specific source object. Once the binding is created, it is bound to the target using the SetBinding method of the target object.

Note

It is always easy to tell what objects support binding, because the object will have the SetBinding method. SetBinding is a method of the FrameworkElement base class.

First, an examination of the example application ...

Get Data-Driven Services with Silverlight 2 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.