Data Binding Using Code

By Michael Detras

Bind properties to your control without the XAML.

Data binding using code is particularly useful when you created a control dynamically and want to bind values to its properties. Here's an example using XAML.

<TextBox x:Name="myTextBox" Text="{Binding Person.Name}"/>

We can achieve the same thing in code like this.

Binding binding = new Binding();
binding.
Source = objectContainingPersonProperty;
binding.
Path = new PropertyPath("Person.Name");
myTextBox.
SetBinding(TextBox.TextProperty, binding);

You can also set the binding mode to OneWay, TwoWay, etc. if you like. This shows that what you can do in XAML, you can do in code.

Related FAQs

Shows an example on how to bind to a property of a UI element using XAML.
This shows how to bind a dependency property to more than 1 binding source using multi-binding.
Data Binding Using Code  (2172 Views)