在后面的代码中绑定到相对源 [英] Binding to a relativesource in the code behind

查看:70
本文介绍了在后面的代码中绑定到相对源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的UserControl中,我的XAML中包含以下代码

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

推荐答案

您应该尝试

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

BindingOperations.SetBinding(this, myProperty, b);

(假设thisDependencyObject,而myProperty是DependencyProperty.

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

这篇关于在后面的代码中绑定到相对源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆