在后面的代码中绑定属性 [英] Binding properties in code behind

查看:26
本文介绍了在后面的代码中绑定属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 WPF 应用程序和一个窗口.让我的 xml 中有这样的东西:

I have WPF application and a window in it. Lets have something like this in my xml:

<Label Name="TitleLabel" Content="Some title" >
<Label Name="BottomLabel" Content="{Binding ElementName=TitleLabel Path=Content">

假设我不能使用 xml 来创建 BottomLabelTitleLabel.所以我必须在我的代码隐藏"中创建底部标签作为属性.如何在后面的代码中为底部标签的 Content 属性指定相同的绑定?有可能吗?

Lets say I don't cannot use xml for creation of BottomLabel and TitleLabel. So I have to create the BottomLabel as a property in my "Code behind". How do I specify the same binding for Content property of Bottom label in my code behind ? Is it possible at all ?

所以我会有这样的事情:

So I would have something like this:

public Label TitleLabel {get; private set;}
public Label BottomLabel {get; private set;}

public MyClass(){
    TitleLabel = new Label();
    TitleLabel.Content = "Some title";
    BottomLabel = new Label();
    BottomLabel.Content = // ?? what should be here ? How do I specify the binding
                          // that binds BottomLabel.COntent to TitleLabel.Content?
}

我可以写什么来代替评论?谢谢你的回答.

What can I write instead of the comment ? Thank you for ansvers.

推荐答案

以下是在代码中定义和应用绑定的方法:

Here's how you define and apply a binding in code:

Binding binding = new Binding {
  Source = TitleLabel,
  Path = new PropertyPath("Content"),
};
BottomLabel.SetBinding(ContentControl.ContentProperty, binding);

请注意,对于不是从 FrameworkElement 派生的对象,您必须明确使用 BindingOperations.SetBinding() 而不是 element.SetBinding():

Note that on objects that don't derive from FrameworkElement, you have to explicitly use BindingOperations.SetBinding() instead of element.SetBinding():

BindingOperations.SetBinding(BottomLabel, ContentControl.ContentProperty, binding);

这篇关于在后面的代码中绑定属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆