代码背后的绑定属性

Ras*_*sto 8 c# xml data-binding wpf

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

<Label Name="TitleLabel" Content="Some title" \>
<Label Name="BottomLabel" Content="{Binding ElementName=TitleLabel Path=Content">
Run Code Online (Sandbox Code Playgroud)

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

所以我会有这样的事情:

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?
}
Run Code Online (Sandbox Code Playgroud)

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

Jul*_*ain 18

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

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

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

BindingOperations.SetBinding(BottomLabel, ContentControl.ContentProperty, binding);
Run Code Online (Sandbox Code Playgroud)