【问题标题】:Copying an ElementName binding复制 ElementName 绑定
【发布时间】:2012-10-12 06:51:55
【问题描述】:

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

然后我有第三个文本框 (TB3),我在 TB1 后面的代码中设置绑定,我希望这将允许我编辑 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();
    }

【问题讨论】:

    标签: c# wpf xaml binding wpf-controls


    【解决方案1】:

    在您的新窗口中,您将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();
    

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

    【讨论】:

    • 感谢 Klaus78,这使我找到了解决方案...请参阅已编辑的问题。
    猜你喜欢
    • 2012-02-25
    • 1970-01-01
    • 2012-07-14
    • 2015-09-02
    • 1970-01-01
    • 2010-11-04
    • 1970-01-01
    • 1970-01-01
    • 2010-09-18
    相关资源
    最近更新 更多