代码背后的绑定属性

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

 

让我们说我不能使用xml来创建BottomLabelTitleLabel 。 所以我必须在我的“Code behind”中创建BottomLabel作为属性。 如何在我的代码后面为Bottom标签的Content属性指定相同的绑定? 有可能吗?

所以我会有这样的事情:

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

我能写什么而不是评论? 谢谢你的回复。

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

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

请注意,对于不是派生自FrameworkElement对象,您必须显式使用BindingOperations.SetBinding()而不是element.SetBinding()

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