wpf WPF绑定到父窗口中的元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20345107/
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
WPF Bind to element in parent window
提问by Slime recipe
I'm trying to bind element's property in a child control to an element's property ina parent window, it doesn't work..
我试图将子控件中元素的属性绑定到父窗口中元素的属性,但它不起作用..
Here is png of what I'm trying to do:

这是我正在尝试做的png:

Here is the xaml that doesn't work:
这是不起作用的 xaml:
CurrentDate="{Binding ElementName=TimeBar, Path=SelectionStart,RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}}"
Thanks.
谢谢。
采纳答案by blindmeis
create a dependency property in your usercontrol and then bind to it in your window
在你的用户控件中创建一个依赖属性,然后在你的窗口中绑定到它
something like that: DependencyProperty implementations you can find all around here on stackoverflow
类似的东西: DependencyProperty implementations you can find all around here on stackoverflow
<YourUsercontrol x:Name="uc">
<YourSomeControl CurrentDate="{Binding ElementName=uc, Path=MyDp}"/>
</YourUsercontrol>
xaml window
xaml 窗口
<Window>
<ElementInParent x:Name="eip" />
<YourUsercontrol MyDp="{Binding ElementName=eip, Path=PropertyFromElementInParent}"/>
回答by WiiMaxx
回答by bhavik shah
Binding ElementName along with Relative Source is not correct approach. Besides the UserControl does not know the ElementName of the Parent since the two are in different XAML.
将 ElementName 与相对源绑定在一起不是正确的方法。此外 UserControl 不知道 Parent 的 ElementName,因为两者在不同的 XAML 中。
One approach is to set the data context of user control with the element name you want to bind it to and then use normal binding Path.
一种方法是将用户控件的数据上下文设置为要绑定到的元素名称,然后使用普通绑定路径。
As shown in the example below: In main window, we have a textbox and a user control. We are setting data context of the user control with the text box.
如下例所示: 在主窗口中,我们有一个文本框和一个用户控件。我们正在使用文本框设置用户控件的数据上下文。
In the user control, we are binding the Text property of the DataContext (which is essentially TextBox of main window).
在用户控件中,我们绑定了DataContext(本质上是主窗口的TextBox)的Text属性。
<Window
xmlns:self="clr-namespace:experiments"
>
<StackPanel>
<TextBox x:Name="Name" Width="100"/>
<self:UserControl1 DataContext="{Binding ElementName=Name}"/>
</StackPanel>
</Window>
<UserControl x:Class="experiments.UserControl1">
<Grid>
<TextBlock Text="{Binding Path=Text}" Width="100" Background="AliceBlue" Height="50"/>
</Grid>
</UserControl>

