Reputation: 6745
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.
Upvotes: 7
Views: 4174
Reputation: 11
Here is nice article about communication between Views in MVVM: Communication Between Views in MVVM (Pub-Sub Pattern)
Upvotes: 1
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
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