我有一个TextBox(TB1),它的Text值绑定到另一个TextBox(TB2),使用ElementName =“TB2”和Path =“Text”。复制ElementName绑定
然后我有第三个文本框(TB3),我在TB1后面的代码中设置绑定,我希望我可以编辑TB3,并且TB1也会反映由于绑定(理论上)所有人都一样。
我可以编辑TB1和TB2更新(反之亦然),但TB3从不显示/更新值。
我只能认为这是因为TB1绑定使用ElementName而不是DependencyProperty?
是否可以复制使用ElementName绑定的元素的绑定?
<TextBox Name="TB1">
<Binding ElementName="TB2" Path="Text" UpdateSourceTrigger="PropertyChanged"/>
</TextBox>
<TextBox Name="TB2">
<Binding Path="Name" UpdateSourceTrigger="PropertyChanged"/>
</TextBox>
然后在后面的代码,我有:
BindingExpression bindExpression = TB1.GetBindingExpression(TextBox.TextProperty);
if (bindExpression != null && bindExpression.ParentBinding != null && bindExpression.ParentBinding.Path != null)
{
TB3.DataContext = TB1.DataContext;
TB3.SetBinding(TextBox.TextProperty, bindExpression.ParentBinding);
}
通常只发现测试刚才说这样做的工作,如果同样的XAML中。但是,我有TB3在它自己的窗口如下,并且文本框永远不会正确绑定..我错过了什么?
if (bindExpression != null && bindExpression.ParentBinding != null && bindExpression.ParentBinding.Path != null)
{
PopupWindow wnd = new PopupWindow();
wnd.DataContext = TB1.DataContext;
wnd.TB3.SetBinding(TextBox.TextProperty, bindExpression.ParentBinding);
wnd.Show();
}
我不是100%肯定,为什么,但这样做有问题,这似乎做同样的绑定,SetBinding但被设置为DataItem的来源,但它给了我所需要的结果...谢谢Klaus78 ..
if (bindExpression != null && bindExpression.ParentBinding != null && bindExpression.ParentBinding.Path != null)
{
PopupWindow wnd = new PopupWindow();
Binding b = new Binding();
b.Source = bindExpression.DataItem; //TB1;
b.Path = new PropertyPath("Text");
b.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
wnd.TB3.SetBinding(TextBox.TextProperty, b);
wnd.Show();
}
谢谢Klaus78,这导致我的解决方案...请参阅编辑的问题。 – gas828