I am building a WPF application with the MVVM design pattern.
I am using DataTemplates to load user controls inside a ContentControl:
<DataTemplate DataType="{x:Type menu:MenuViewModel}">
<menu:MenuView/>
</DataTemplate>
<ContentControl Content="{Binding Menu}" Visibility="{Binding MenuVisibility,
Converter={StaticResource BooleanToVisibility}}"/>
In addition to the menu I have a user control to handle the StatusBar and this is where the question arises. So that the other ViewModels can interact with the StatusBar, what I have done is create a MainViewModel in each ViewModel that needs this functionality and then assign it from the MainViewModel like this:
_ChatViewModel.mainViewModel = this;
CurrentViewModel = _ChatViewModel;
This works, but I think there must be an invented "wheel" and I'm getting complicated. Is there a more "simple", "standard" way that I'm overlooking?
To communicate viewmodel you should use events, you could apply the pattern
Publish/Subscribe
.It
MainViewModel
exposes an event (in your case to update the statusbar), and those who want to report a change simply fire the same event respecting the signature and sending the arguments.In this way you decouple the communication.
Communication Between Views in MVVM (Pub-Sub Pattern)
If you apply any library, they include this concept such as
MVVM Light’s Messenger
orMicrosoft Prism’s EventAggregator
.Communication between ViewModels with MVVM