简体   繁体   English

WPF绑定到父窗口中的元素

[英]WPF Bind to element in parent window

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: 这是我正在尝试做的事情: 在此输入图像描述

Here is the xaml that doesn't work: 这是不起作用的xaml:

CurrentDate="{Binding ElementName=TimeBar, Path=SelectionStart,RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}}" 

Thanks. 谢谢。

create a dependency property in your usercontrol and then bind to it in your window 在usercontrol中创建依赖项属性,然后在窗口中绑定它

something like that: DependencyProperty implementations you can find all around here on stackoverflow 类似的东西:你可以在stackoverflow上找到所有的DependencyProperty实现

<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}"/>

根据以下答案链接 ,SelectionStart默认情况下不是Bindable Probperty,因此您需要创建附加行为或类似的东西

Binding ElementName along with Relative Source is not correct approach. 绑定ElementName和Relative Source是不正确的方法。 Besides the UserControl does not know the ElementName of the Parent since the two are in different XAML. 除了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的Text属性(主要是主窗口的TextBox)。

<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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM