绑定到后面的代码中的relativesource

Dav*_*ave 6 c# wpf binding

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

<TextBlock Grid.Row="2" Text="{Binding Path=StartTime,
                               RelativeSource={RelativeSource Mode=FindAncestor,
                                AncestorLevel=1, AncestorType=Window}}" />
Run Code Online (Sandbox Code Playgroud)

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

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

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
Run Code Online (Sandbox Code Playgroud)

Roh*_*ats 14

x:Name你的TextBlock -

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

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


geh*_*hho 10

你应该试试BindingOperations.SetBinding.这应该是这样的:

BindingOperations.SetBinding(this, myProperty, b);
Run Code Online (Sandbox Code Playgroud)

(假设这this是一个DependencyObject并且myProperty是DependencyProperty.