andySF
andySF

Reputation: 604

MVVMLight open view with parameter

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?

Upvotes: 0

Views: 230

Answers (1)

Gianluca Conte
Gianluca Conte

Reputation: 490

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

Upvotes: 2

Related Questions