At times, you may find that you need to bind the property of a control in the code behind. This is possible using the GetBindingExpression
and SetBinding
methods on the control.
To create a new binding and assign it to a control property, simply instantiate a Binding
object (found in the System.Windows.Data
namespace), assign the binding configuration to its properties as required, and apply the binding to the target control property using the control's SetBinding
method. The SetBinding
method requires you to pass it the Binding
object and the dependency property identifier associated with the property to bind to on the target control, remembering that you can assign data bindings only to dependency properties.
For example, let's bind the Name
property of a Product
entity to the Text
property of a TextBox control named NameTextBox
:
Binding binding = new Binding("Name");
binding.Mode = BindingMode.TwoWay;
NameTextBox.SetBinding(TextBox.TextProperty, binding);
This example of creating a binding in code is simple, but of course, you can assign values to all the other binding properties that we have previously discussed, such as StringFormat
, TargetNullValue
, FallbackValue
, and Source
.
You can obtain the binding assigned to a control's property using the GetBindingExpression
method on the control.
BindingExpression expr = NameTextBox.GetBindingExpression(TextBox.TextProperty);
As its name suggests, this method does not actually return a Binding
object but returns a BindingExpression
object instead. The BindingExpression
class has two properties: ParentBinding
and DataItem,
in addition to the UpdateSource
method discussed earlier. The ParentBinding
property provides the Binding
object assigned to the control property, and the DataItem
property provides the object acting as the source for the binding.