I am newbie to WPF and MVVM and I am trying to learn how WPF working with MVVM. For that, I have made a sample as follows
UserControl1.xaml
<StackPanel>
<TextBox Text="{Binding MyString}" />
</StackPanel>
UserControl1ViewModel.cs
class UserControl1ViewModel
{
public string MyString { get; set; }
}
MainWindow.xaml
<StackPanel>
<local:UserControl1 DataContext="{Binding UC1Property}"/> //tried binding the Usercontrol1VM obj on MainWindowVM
<Button Command="{Binding ShowMeOne}" Height="30" Content="ShowOne"/>
<Button Command="{Binding ShowMeAnother}" Height="30" Content="ShowAnother" />
</StackPanel>
MainWindow.xaml.cs
public MainWindow()
{
InitializeComponent();
this.DataContext = new MainWindowViewModel();
}
MainWindowViewModel.cs
class MainWindowViewModel
{
public MainWindowViewModel()
{
ShowMeOne = new RelayCommand(Prompt_ShowMeOne);
ShowMeAnother = new RelayCommand(Prompt_ShowMeAnother);
UC1Property.MyString = "Initial";
}
private void Prompt_ShowMeAnother(object obj)
{
global::System.Windows.MessageBox.Show("Another Should be shown");
UC1Property.MyString = "Last Clicked: Another";
}
private void Prompt_ShowMeOne(object obj)
{
global::System.Windows.MessageBox.Show("One Should be shown");
UC1Property.MyString = "Last Clicked: One";
}
public ICommand ShowMeOne { get; set; }
public ICommand ShowMeAnother { get; set; }
//UserControl1 View Model for MainWindow
public UserControl1ViewModel UC1Property { get; set; }
}
Problem: Now, how can I pass the Datacontext of the Usercontrol into the MainWindow?
-----------------------------In MainWindow.xaml----------------------
<local:UserControl1 DataContext="{Binding UC1Property}"/> //tried binding the Usercontrol1VM obj on MainWindowVM
-----------------------------In MainWindowViewModel.cs---------------
//UserControl1 View Model for MainWindow
public UserControl1ViewModel UC1Property { get; set; }
Above code which I tried is not working as expected. What is the standard way of passing the datacontext of usercontrol over the window?