Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVVM - Communication between Separated Views

Tags:

mvvm

wpf

I'm trying to figure out how to do the following:

I have a CustomerListViewModel that contains a ObservableCollection<Customer>

MainView holds an instance of these views:

  • CustomerListView - which creates an instance of CustomerListViewModel
  • SearchView - which creates and instance of SearchViewModel

My question is, How do I keep the CustomerListView and the SearchView separated. The SearchView should only be displayed if a Customer is selected. The only dependency for the SearchViewModel should be a Customer Model. If there isn't a Customer selected from the CustomerListViewModel, then the SearchView shouldn't be displayed.

Should I introduce a new View/ViewModel that contains both a CustomerListViewModel and SearchViewModel that can hold a reference to the Selected Customer and toggle the displaying of a SearchView? If not, how should I go about this?

I know this question is pretty broad, but I would appreciate any suggestions.

like image 710
Michael G Avatar asked Jun 08 '11 15:06

Michael G


1 Answers

Don't make MainView contain instances of CustomerListView and SearchView. All three of them should be separate.

As far as the communication between views is concerned, this should be done through the respective viewmodel using e.g mvvm-light messenger. If you register a different messenger with each view, then from a viewmodel you can send message to any view you want.

Just an example of the simplicity of using an MVVMLight Messenger:-

View:

Messenger.Default.Register<NotificationMessage>(this, OpenViewMessageReceived);

private void OpenViewMessageReceived(NotificationMessage msg)
{
    //Logic 
}

ViewModel:

Messenger.Default.Send(new NotificationMessage(someStr));
like image 119
Hasan Fahim Avatar answered Sep 20 '22 11:09

Hasan Fahim