Michael G
Michael G

Reputation: 6745

MVVM - Communication between Separated Views

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:

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.

Upvotes: 7

Views: 4174

Answers (4)

Richard
Richard

Reputation: 11

Here is nice article about communication between Views in MVVM: Communication Between Views in MVVM (Pub-Sub Pattern)

Upvotes: 1

Hasan Fahim
Hasan Fahim

Reputation: 3885

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));

Upvotes: 4

Rachel
Rachel

Reputation: 132548

I actually wrote something recently that dealt with that here. You might be interested in checking it out.

Basically, if you can access your value from a RelativeSource Binding that is probably the simpliest way to do it

Something like {Binding RelativeSource={RelativeSource AncestorType={x:Type local:MainView}}, Path=DataContext.CustomerListViewModel.SelectedCustomer}

Or implement a messaging system that broadcasts a message whenever the SelectedCustomer gets changed. MVVM Light Toolkit has a nice simple one using the Messenger class, or Prism had the more advanced EventAggregator.

Upvotes: 1

opiswahn
opiswahn

Reputation: 465

If it's not to 'overkill' for you, you may checkout PRISM

It's a guideline with library for composite applications using MVVM and MEF. It's a very neat lib, but for small projects it might be oversized.

Upvotes: 0

Related Questions