Dave
Dave

Reputation: 8451

Binding to a relativesource in the code behind

In my UserControl, I have the following code in my XAML

<TextBlock Grid.Row="2" Text="{Binding Path=StartTime,
                               RelativeSource={RelativeSource Mode=FindAncestor,
                                AncestorLevel=1, AncestorType=Window}}" />

This simply gets the value of a property from the parent window and it works great.

How can I do this in the code behind?

Binding b = new Binding();
b.RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor,
                                      typeof(Window), 1);
b.Path = "StartTime";

myProperty = b.value;// obviously there is no b.value but this
                     // is what I'm trying to achieve.

//BindingOperations.SetBinding(StartTime, StartTimeProperty, b);
//This does not work sadly, it can't convert string to DependancyObject

Upvotes: 10

Views: 17851

Answers (2)

Rohit Vats
Rohit Vats

Reputation: 81233

Give x:Name to your TextBlock -

then you can do that in code behind like this -

Binding b = new Binding("StartTime");
b.RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor,
                                         typeof(Window), 1);
textBlock.SetBinding(TextBlock.TextProperty, b);

Upvotes: 20

gehho
gehho

Reputation: 9238

You should try BindingOperations.SetBinding. This should work something like this:

BindingOperations.SetBinding(this, myProperty, b);

(assuming that this is a DependencyObject and myProperty is the DependencyProperty.

Upvotes: 11

Related Questions