10

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 

2 Answers 2

20

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); 
Sign up to request clarification or add additional context in comments.

Comments

11

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.

3 Comments

I had tried this, but I didn't' use this I used the property instead.
It would be helpful if you posted the code which contains the declaration of myProperty. In my example, this must be a DependencyObject (e.g. a Control), and myProperty must be a DependencyProperty. I assume this is not the case. You might have to change myProperty to something like MyClass.MyProperty (the static DependencyProperty field.
Sorry, my message wasn't meant to say your example is wrong, more that I was doing it wrong! Your example is what I wanted. Thanks

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.