绑定到后面的代码中的relativesource

在我的UserControl中,我在XAML中有以下代码

 

这只是从父窗口获取属性的值,它工作得很好。

我怎么能在后面的代码中执行此操作?

 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 

您应该尝试BindingOperations.SetBinding 。 这应该是这样的:

 BindingOperations.SetBinding(this, myProperty, b); 

(假设this是一个DependencyObjectmyProperty是DependencyProperty。

x:Name赋予TextBlock –

那么你可以在代码背后这样做 –

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