wpf 绑定到后面代码中的相对源

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19793613/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 10:01:06  来源:igfitidea点击:

Binding to a relativesource in the code behind

c#wpfbinding

提问by Dave

In my UserControl, I have the following code in my XAML

在我的 UserControl 中,我的 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

回答by Rohit Vats

Give x:Nameto your TextBlock -

x:Name你的 TextBlock -

then you can do that in code behind like this -

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

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

回答by gehho

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

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

BindingOperations.SetBinding(this, myProperty, b);

(assuming that thisis a DependencyObjectand myPropertyis the DependencyProperty.

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