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

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

问题描述

我有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创造 BottomLabel TitleLabel 。所以我要创建BottomLabel在我的背后代码的属性。如何指定同为内容底部的标签属性在我后面的代码绑定? ?是否有可能在所有

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 ?

所以我有这样的事情:

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?
}



可我写的是什么,而不是评论?
感谢您ansvers

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天全站免登陆