繁体   English   中英

复制ElementName绑定

[英]Copying an ElementName binding

我有一个TextBox(TB1),它的Text值使用ElementName =“ TB2”和Path =“ Text”绑定到另一个TextBox(TB2)。

然后,我有第三个TextBox(TB3),它是TB1后面的代码中的SetBinding,我希望它可以让我编辑TB3,并且TB1和TB2都将反映出更改,因为绑定(理论上)对于所有对象都是相同的。

我可以编辑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();
    }

在新窗口中,将TB3.Text绑定到TB2.Text

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

还要注意, TB1.DataContext为空。 另一方面,该命令没有用,因为绑定类已经设置了Element属性,它是绑定源。

我认为您不能简单地将绑定从TB1复制到TB3。 无论如何,您需要为TB3创建一个新的Binding对象,例如

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

这样的代码对您有帮助吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM