开发者

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

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?


Try this

Xaml

<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);


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);


I know there's already an accepted answer, but is there some reason you're just not doing this?

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

Now whatever textBox1 is bound to, even if that binding changes, textBox2 is as well, no code-behind needed.

Granted I'm basing this on the XAML as presented, and you very well may need the binding itself from code for something else, but if not, the above works just fine.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜