[英]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. textBox绑定到某些数据。 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. 所以我想将文本框2绑定到第一个textBox绑定的相同数据。
In other words I wan't to know if the DependencyObject stores some reference to it's data-bindings? 换句话说,我不知道DependencyObject是否存储了对它的数据绑定的一些引用? If not, what is the way to find out all data-bindings of a specific object? 如果没有,找出特定对象的所有数据绑定的方法是什么?
Try this 尝试这个
Xaml 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 然后我们可以将textBox2的TextProperty与textBox1的绑定设置为后面的代码
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. 现在无论textBox1
绑定了什么,即使该绑定发生了变化, textBox2
也是如此,不需要代码隐藏。
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. 当然,我将这个基于XAML,你很可能需要从代码中绑定其他东西,但如果没有,上面的工作就好了。
您可以通过调用SetBinding
方法在代码中执行此操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.