In WPF how to get binding of a specific item from the code?

0 votes
asked Oct 29, 2010 by vitalij

The example of this would be:

A textBox is bound to some data. There is a second text box which is not bind to anything. So I want to bind text box 2 to the same data 1st textBox is bound.

In other words I wan't to know if the DependencyObject stores some reference to it's data-bindings? If not, what is the way to find out all data-bindings of a specific object?

3 Answers

0 votes
answered Oct 29, 2010 by peter-van-kekem

You can do this in code by calling the SetBinding method.

0 votes
answered Oct 29, 2010 by fredrik-hedblad

Try this


<TextBox Name="textBox1" Text="{Binding Text1}"/>
<TextBox Name="textBox2" Text="No Binding"/>

Then we can set the binding of the TextProperty for textBox2 to the same as textBox1 with this code behind

BindingExpression bindingExpression = textBox1.GetBindingExpression(TextBox.TextProperty);
Binding parentBinding = bindingExpression.ParentBinding;
textBox2.SetBinding(TextBox.TextProperty, parentBinding);
0 votes
answered Oct 6, 2016 by felipe-faria

You can get the binding of any dependency object using

System.Windows.Data.BindingOperations.GetBinding(DependencyObject target,DependencyProperty dp)

then set the binding with

System.Windows.FrameworkElement.SetBinding(DependencyProperty dp, string path)

For example:

var binding = BindingOperations.GetBinding(textBox1,TextBox.TextProperty);
textBox2.SetBinding(TextBox.TextProperty, binding);
Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter