I'm using Prism/MVVM/WPF and have ViewModels:
public class ViewModelP : BindableBase
{
private string _stringP;
public string StringP
{
get => _stringP;
set => SetProperty(ref _stringP, value);
}
private ObservableCollection<ViewModelQ> _myQs
public ObservableCollection<ViewModelQ> MyQs
{
get => _myQ;
set => SetProperty(ref _myQ, value);
}
}
public class ViewModelQ : BindableBase
{
private string _stringQ;
public string StringQ
{
get => _stringQ;
set => SetProperty(ref _stringQ, value);
}
}
And then I have a View:
<UserControl x:Class="NamespacePath.ViewP"
xmlns:local="NamespacePath"
d:DataContext="{d:DesignInstance Type=local:ViewModelP, IsDesignTimeCreatable=False}">
<!--I left out most of the boilerplate declarations from UserControl-->
<DockPanel>
<TextBlock Text={Binding StringP}/> <!--This binding works-->
<TabControl ItemsSource={Binding MyQs}>
<TabControl.Resources>
<DataTemplate DataType="{x:Type local:ViewModelQ}">
<DockPanel>
<TextBlock Text="{Binding StringP}"/> <!--This binding does not work-->
<TextBlock Text="{Binding StringQ}"/> <!--This binding works-->
</DockPanel>
</DataTemplate>
</TabControl.Resources>
</TabControl>
</DockPanel>
</UserControl>
I know that ViewModelQ's do not inherently have any reference to ViewModelP, but is it possible to, in the View, bind to the DataContext of the parent control (the User Control)?
ViewModelQ? Why should it be relevant, considering that the TabControl is bound to a collection ofQ?Text="{Binding DataContext.StringP, RelativeSource={RelativeSource AncestorType=TabControl}}"- if that was your question.