代码背后的绑定属性

时间:2010-05-30 12:42:55

标签: c# wpf xml data-binding

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

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

假设我不能使用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?
}

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

1 个答案:

答案 0 :(得分:16)

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

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);