In my WPF application I have a MainWindow.xaml which has many User Controls embedded into it. I have separate viewmodel for both the main window as well as the user controls. In the Main Window ViewModel I create an instance of the child ViewModel and set it as the child's datacontext.
Parent VM ChildUserControlVM ChildVM = new ChildUserControlVM (ParentModel.ChildModel);
MainWindow.xaml
But this approach is not working as I am not getting the values set in the parent viewmodel in the child one and vice versa.
On the contrary, if I set the Child model object as the datacontext from the parent that is working both way.
I need some solution so that I can use MVVM in the user controls also ensuring data gets passed from parent to child and vice versa. In the usercontrol I am going to have some buttons whose action I want to handle in the child Viewmodel through ICommand. Adding the code snippets for reference MainWindow.xaml
<Grid Grid.Row="0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Margin="0,0,0,0">
<local:ProfileIdentitySettings Visibility="{Binding ProfileIdentitySettingsVisibility,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}" DataContext="{Binding ChildProfileIdentityVM}"/>
</Grid>
MainWindowVM.cs
ProfileIdentitySettingsVM ChildProfileIdentityVM = new ProfileIdentitySettingsVM(DeviceEditorModel.ProfileIdentitySettings);
ProfileIdentitySettings.xaml
DataContext="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.MainWindowVM}">