How can I create a data binding in code using WPF?

When creating UI elements in code it is often necessary to programmatically bind them to data. Fortunately this is relatively straightforward as the following code-snippet using the Binding object from the System.Windows.Data namespace shows:

C# Source (WPF Beta 2)
TextBox nameTextBox = new TextBox();
Binding nameTextBinding = new Binding("Name");
nameTextBinding.Source = person;
nameTextBox.SetBinding(TextBox.TextProperty, nameTextBinding);
// set style on text box, add text box to container etc

This sample assumes you have a type called Person, and an instance called person created elsewhere. Person has a public property called name. First we create our text box (called nameTextBox) and a Binding object, setting the path string for the binding in the constructor. Then we set the data source to the person instance. Alternatively the nameTextBox could get its data through its DataContext or the DataContext of one of its ancestors. If this was the case setting the Source property on the binding would not be necessary.

Next we call the SetBinding() method on the nameTextBox instance, specifying a DependencyProperty and the binding we just created. The example above binds the TextProperty DependencyProperty of nameTextBox to the Name property of the person. In this case the DependencyProperty is a member of the TextBox itself, but it doesn't have to be. For example we can also bind attached properties that might pertain to the container the nameTextBox is placed in.

This example below binds (rather pointlessly) the TopProperty DependencyProperty of the Canvas to the current number of minutes that have elapsed in the current hour for a newly created textbox instance. If the textbox is then added to a canvas (the example assumes a canvas called mainCanvas) the binding will take effect, controlling the top of the textbox in the canvas.

C# Source (WPF Beta 2)
TextBox positionedTextBox = new TextBox();
Binding positionBinding = new Binding("Minute");
positionBinding.Source = System.DateTime.Now;
positionedTextBox.SetBinding(Canvas.TopProperty, positionBinding);

Pingback from

Bind to XAML in code | Q Sites

1/07/2013 4:12:00 PM
Pingback from

wpf binding when using datatemplate | Search RounD

10/03/2014 1:23:55 AM
Pingback from

How do I programmatically bind a ContentControl’s content to the DataContext? | Zehe Answers

10/12/2014 10:26:22 AM