Data Bind Using Only Code Behind

We are all familiar with the use of WPF Binding in XAML. For example, the following lines bind the caption of a Button (variableCaptionButton) to the text of a TextBox (sourceText).

<TextBox x:Name="sourceText" Grid.Row="0" />
<Button x:Name="variableCaptionButton" Grid.Row="1" Content="{Binding ElementName=sourceText, Path=Text}"/>

 

Have there been times when you need to dynamically build or add UI elements from code behind and have a need to also create bindings among those dynamically created UI elements?

Creating binding using only code behind is easy.

Here is the code behind to accomplish the same binding shown in the above XAML code.

Binding binding = new Binding("Text");
binding.Source = sourceText;
variableCaptionButton.SetBinding(Button.ContentProperty, binding);

 

The Binding instance defines the data source (the “sourceText” TextBox), and which data source property (the “Text” property). SetBinding() connects a binding source to the receiving property on the target element (“variableCaptionButton” button).

Additionally, you can also define a value converter and parameter via the properties, Binding.Converter and Binding.ConverterParameter, respectively.

That’s it!

-Tan