2012-10-22 46 views
0

我有一个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(); 
    } 

回答

1

在新的窗口中,您绑定TB3.TextTB2.Text

在实践TB3.Text你有一个绑定OBJET其中Element=TB2Path=Text。问题是在新窗口的可视化树中没有名称为TB2的元素,因此如果您查看Visual Studio输出调试,则会出现绑定错误。

另请注意TB1.DataContext为空。另一方面,这个命令是无用的,因为绑定类已经具有绑定源的属性集合Element

我认为你不能简单地将绑定从TB1复制到TB3。无论如何,你需要创建一个TB3像

Window2 wnd = new Window2(); 
Binding b = new Binding(); 
b.Source = TB1; 
b.Path = new PropertyPath("Text"); 
wnd.TB3.SetBinding(TextBox.TextProperty, b); 
wnd.Show(); 

一个新的绑定对象可以像一些代码对你有所帮助?

+0

谢谢Klaus78,这导致我的解决方案...请参阅编辑的问题。 – gas828

相关问题