-1

I have a MainWindowView that has a grid with 2 columns each having 1 UserControl View. MainWindowView constructor creates instance of MainWindowVM and sets the data context to this new instance.

this.DataContext = new MainWindowVM(this)

Now question is I am trying to set data context of each UserControlView to an instance of it's respective ViewModel inside MainWindowVM. How can I access the UserControlView inside MainWindowVM to do something like this

UserControl1View.DataContext= new UserControl1ViewModel()

If I can do this, it will allow me to use MainWindowVM as a common hub holding all kinds of event subscriptions from the 2 userControls.

  • 1
    Don't do this. MainWindowVM should expose properties for its child view model. Bind a UserControl's DataContext (or that of its parent element) to such a child view model in XAML, like `view1.DataContext="{Binding View1VM}"` – Clemens Mar 31 '18 at 06:03
  • Where View1VM is a bindable property of MainWindowViewModel. – Andy Mar 31 '18 at 10:08

2 Answers2

0

ViewModel must not depend upon View, and both must have one-to-one relationship between them. So best is to use Binding to set DataContext and if this setting of DataContext depends upon some condition, then use Triggers.

AnjumSKhan
  • 9,647
  • 1
  • 26
  • 38
0

Don't-Do-That.

A better approach is to have a ViewModel reference in he View.

Create an interface similar to this:

public interface IView<T> where T : class
{
    T ViewModel;
}

Now, your Views must implement that interface

public partial class MainView : Window, IView<MainViewModel>
{
    public MainViewModel ViewModel { get; set; }

And inject the ViewModel in the view constructor:

public MainView(MainViewModel vm)
{
    this.ViewModel = vm;
    this.DataContext = this.ViewModel;
    // you can create the VMs you want for the another views
    var vm1 = new UserControl1ViewModel();
    // and pass it to the UserControl1View (UserControl1View implements IView<T>
    var view1 = new UserControl1View(vm1);
Luis
  • 436
  • 4
  • 11