Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding to a relativesource in the code behind

Tags:

c#

binding

wpf

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
like image 594
Dave Avatar asked Nov 05 '13 16:11

Dave


2 Answers

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);
like image 195
Rohit Vats Avatar answered Oct 21 '22 20:10

Rohit Vats


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.

like image 29
gehho Avatar answered Oct 21 '22 18:10

gehho