在我的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
答案 0 :(得分:13)
将x:Name
提供给TextBlock -
那么你可以在这样的代码中做到这一点 -
Binding b = new Binding("StartTime");
b.RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor,
typeof(Window), 1);
textBlock.SetBinding(TextBlock.TextProperty, b);
答案 1 :(得分:9)
您应该尝试BindingOperations.SetBinding
。这应该是这样的:
BindingOperations.SetBinding(this, myProperty, b);
(假设this
是DependencyObject
而myProperty
是DependencyProperty。