0

I'm trying to learn MVVMLight and I'm stuck at creating a new view for editing an object.

I have CustomersView with CustomersViewModel that display a datagrid with customers. On double click on DataGridRow, I open a CustomerView that implements a CustomerViewModel to edit the customer and I'm using this code in CustomersViewModel:

 var cv=new CustomerView();
 var cvm=new CustomerViewModel();
 cvm.IsEdit = true;
 cvm.Customer = customer;
 cv.DataContext = cvm;
 cv.ShowDialog();

Is this a bad approach? What is the best way to create a view, instantiating the view model with some parameters?

andySF
  • 556
  • 7
  • 30
  • 1
    I asked a [similar question](https://stackoverflow.com/questions/51327993/how-can-i-initialize-a-property-in-a-viewmodel-when-creating-a-new-view) earlier. You can instate your viewmodel with DI and then directly modify properties – James Parsons Jul 23 '18 at 19:21

1 Answers1

2

Ba aware that if you instantiate a view object such CustomerView inside your viewModel you shall break the mvvm pattern. That's should be a problem if your project will grow.

If you absolutely want to mantain the mvvm pattern you have two options:

1) Create an interface like

interface INavigationService
{
    NavigateTo(string viewName ,objet params);
}

Create a singleton implementation of this class. Put the logic tht creates new CustomerView() and other views inside this method. The main goal is to separate view from anything else. Try to use injection to have only the INavigationService reference inside your viewmodels.

2) Use a very heavy framework for mvvm like Prism;

EDIT: mvvm ligth 5.0 offers its own INavigationService interface. You can decide to implement it if you are using this version. It doesn't provide any implementation... see MVVM Light 5.0: How to use the Navigation service

Gianluca Conte
  • 480
  • 4
  • 8
  • Thank you. The implementation is for pages. I will try to understand how to use that service to open windows. – andySF Jul 24 '18 at 05:53