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
                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);
                        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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With