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();
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With