Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Right Way to access a View Model from an existing View Model

Tags:

c#

mvvm

wpf

prism

I am somewhat new to MVVM. I am not sure what the best way is to do what I am trying to do.

Here is the scenario:

I have a VM that is going to show another window. I can call myNewWindowView.Show(), but first I need to set some data in the VM of my new window.

Should I expose both the myNewWindowView and the NewWindowViewModel to the calling ViewModel?

Here is an example:

class MainVM
{
    public void FindCustomer(string nameParial)
    {
       List<Customer> customers = ServiceCall.GetCustomers(nameParital);
       // This is the part I am not sure how to do.  I am not sure if this
       //  View Model should have a reference to a different view model and
       //  the view too.
       myNewWindowViewModel.CustomerList = customers;
       myNewWindowView.Show();
    }
}
like image 343
Vaccano Avatar asked Oct 31 '10 18:10

Vaccano


1 Answers

I would keep the viewmodel separate from any view. I tend to think of them as layers, but they are only interchangeable in one direction.

So a model of type foo can have any view model layered on top of it, and it never expects or cares about the viewmodel type.

A viewmodel can only be for one type of model, but it doesn't care or expect what type of view will use it.

A view will be for a particular type of viewmodel.

What you seem to have is a viewmodel the cares about what views are doing, which seems wrong to me.

If it were me, I'd get the view for the MainVM to display the new window, getting the MainVM to pass out the appropriate viewmodel for the new window.

This is the code I would put behind the view for the main viewmodel

class MainWindow : Window
{
     public MainWindow()
     {
          Initialize();
          DataContext = new MainVM();
     }

     public void FindCustomerClick(object sender, RoutedEventArgs args)
     {
          CustomerListView clv = new CustomerListView();
          clv.DataContext = (DataContext as MainVM).FindCustomer(search.Text);
          clv.Show();
     }
}

As you can see, the viewmodel has a method that takes a string and returns a CustomerListViewModel, which is then applied to the DataContext of a CustomerListView.

like image 123
Matt Ellen Avatar answered Sep 28 '22 05:09

Matt Ellen