9

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

<TextBlock Grid.Row="2" Text="{Binding Path=StartTime,
                               RelativeSource={RelativeSource Mode=FindAncestor,
                                AncestorLevel=1, AncestorType=Window}}" />

这只是从父窗口获取属性的值,效果很好。

我怎样才能在后面的代码中做到这一点?

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
4

2 回答 2

18

x:Name你的 TextBlock -

然后你可以像这样在后面的代码中做到这一点 -

Binding b = new Binding("StartTime");
b.RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor,
                                         typeof(Window), 1);
textBlock.SetBinding(TextBlock.TextProperty, b);
于 2013-11-05T17:09:05.410 回答
10

你应该试试BindingOperations.SetBinding。这应该像这样工作:

BindingOperations.SetBinding(this, myProperty, b);

(假设this是 aDependencyObject并且myProperty是 DependencyProperty。

于 2013-11-05T16:19:34.857 回答