{Binding RelativeSource = {RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=Name}
Here you say that WPF will find the first parent of this control using the Type window, for example. this is "ParentWindow". After this binding occurs with the property name "ParentWindow".
If you want to enable binding to a control that is defined in the same XAML, you can explicitly set the source using the Binding.ElementName property. This is a sample code:
<TextBlock Text = "{Binding ElementName=Name, Path=Text}"/>
By the way, using the control name as "Name" is not good. If you use this control form code for it, looking like Name.Text = "some text", which can cause problems with understanding what is happening.
UPDATE: Example binding to managing a DataContext property in another datatemplate
class MainViewModel { public Class1 C1 { get; set; } public Class2 C2 { get; set; } public MainViewModel() { C1 = new Class1 { S1 = "This is C1 data context" }; C2 = new Class2 { S2 = "This is C2 data context" }; } }
In XAML:
<Window x:Class="WpfApplication1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WpfApplication1" Title="MainWindow" Height="350" Width="525"> <Window.Resources> <DataTemplate DataType="{x:Type local:MainViewModel}"> <StackPanel> <ContentControl Name="cc1" Content="{Binding C1}"/> <ContentControl Name="cc2" Content="{Binding C2}"/> </StackPanel> </DataTemplate> <DataTemplate DataType="{x:Type local:Class1}"> <TextBlock Text="{Binding S1}"/> </DataTemplate> <DataTemplate DataType="{x:Type local:Class2}"> <TextBlock Text="{Binding ElementName=cc1, Path=DataContext.C1.S1}"/> </DataTemplate> </Window.Resources> <Grid> <ContentControl Content="{Binding}"/> </Grid> </Window>
But I donβt think that something like this is a good approach. Especially because it can be many elements with this DataTemplate. You might need to delegate this to your ViewModel.
source share