views:

36

answers:

1

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">

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.

+2  A: 

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

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);
Julien Lebosquain
I guess that I'll have to use `BindingOperations.SetBinding()` as my target object is of type `AnimationTimeline`. I think I can figure out how to do it but could you please provide example also for this scenario? At least it will be useful for those that will read your answer later. Thank you.
drasto
Done with your initial sample, just replace the first parameter with your timeline and the second with the DP to bind (eg `Timeline.DurationProperty`).
Julien Lebosquain