7

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: enter image description here

Here is the xaml that doesn't work:

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

Thanks.

Slime recipe
  • 2,223
  • 3
  • 32
  • 49
  • 2
    You can't use `ElementName` and `RelativeSource` together. – Arian Motamedi Dec 03 '13 at 07:25
  • 2
    Using ElementName does not require you to use RelativeSource, omit RelativeSource and it should work.. – S2S2 Dec 03 '13 at 07:26
  • If I omit the RelativeSource I no longer get an exception. but the output window prints an error "System.Windows.Data Error: 4 : Cannot find source for binding with reference 'ElementName=TimeBar'" – Slime recipe Dec 03 '13 at 07:35

3 Answers3

4

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

<YourUsercontrol x:Name="uc">
  <YourSomeControl CurrentDate="{Binding ElementName=uc, Path=MyDp}"/>
 </YourUsercontrol>

xaml window

 <Window>
   <ElementInParent x:Name="eip" />
   <YourUsercontrol MyDp="{Binding ElementName=eip, Path=PropertyFromElementInParent}"/>
blindmeis
  • 22,175
  • 7
  • 55
  • 74
0

based on the following Answer LINK the SelectionStart is not a Bindable Probperty by default so you need to create a attached behavior or something similar

Community
  • 1
  • 1
WiiMaxx
  • 26
  • 3
0

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.

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

<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>
bhavik shah
  • 573
  • 5
  • 12
  • What about if it's not a user control, and its a child window that is bound to a parent window's property – Epirocks Jul 21 '17 at 23:36
  • I think that should work in general but I have to check to be sure and get back. One assumption here is that the child window is modal dialog. – bhavik shah Jul 30 '17 at 11:38