I have a main window with a user control in a content control
<MainWindow Title="MainWindow"> <!-- MainWindows DataContext is set to MainWindowViewModel --> <ContentControl Content="{Binding CurrentViewModel}"> <ContentControl.Resources> <DataTemplate DataType="{x:Type viewmodels:ViewModel1}"> <local:UserControl1/> </DataTemplate> </ContentControl.Resources> <ContentControl/> <MainWindow/> And a User Control with a text box
<UserControl Title="UserControl1"> <TextBlock Text="{Binding Path=Words}"/> <UserControl/> And a MainWindowViewModel
public class MainWindowViewModel { private ViewModelBase _currentViewModel; public ViewModelBase CurrentViewModel { get { return _currentViewModel; } set { _currentViewModel = value; OnPropertyChanged("CurrentViewModel"); } } private string _words; public string Words { get { return _words; } set { _words = value; OnPropertyChanged("Words"); } } } How do I bind the textblocks text to the Words property? I tried this but it isnt working...
<TextBlock Text="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ContentControl}}, Path=DataContext.Words}" />
UserControlis a subclass ofContentControl, the RelativeSource will resolve to your UserControl. You could try specifyingAncestorLevel(see stackoverflow.com/questions/15237037/…).<ContentControl Content="{Binding CurrentViewModel}">when you want the UserControl to bind to a property of MainWindowViewModel? Try<ContentControl Content="{Binding}">. The RelativeSource Binding is (again) pointless.<DataTemplate DataType="{x:Type viewmodels:MainWindowViewModel}">.<local:UserControl1 Prop1="{Binding PropFromCurrentVm}" Words="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ContentControl}}, Path=DataContext.Words}"/>