0

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}" /> 
7
  • yes, I do mean that Commented Sep 27, 2021 at 1:04
  • As UserControl is a subclass of ContentControl, the RelativeSource will resolve to your UserControl. You could try specifying AncestorLevel (see stackoverflow.com/questions/15237037/…). Commented Sep 27, 2021 at 1:11
  • Why do you set <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. Commented Sep 27, 2021 at 5:41
  • You would of course also need <DataTemplate DataType="{x:Type viewmodels:MainWindowViewModel}">. Commented Sep 27, 2021 at 6:31
  • In case you have a UserControl that really simultaneously binds to different view models, consider a different approach. Instead of directly accessing the view models in the UserControl's XAML, let the control expose a set of bindable properties that would be bound to properties of different view models when you use the control, like <local:UserControl1 Prop1="{Binding PropFromCurrentVm}" Words="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ContentControl}}, Path=DataContext.Words}"/> Commented Sep 27, 2021 at 6:36

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.