问题
i was at the bar and i had couple beers, and this girl was arguing that getting mvvm to work with a real world applications is pain, she said that in order to solve problem in mvvm you add more code then you get another problem and the you add more code and it never ends, and i agree, when i read about mvvm it sounded nice, and i don't want to use prism nor MVVM light, i just need a way to switch between my views. and my application looks like this so please inspire me before i get alcohol poisoning
回答1:
If you want loosely-coupled communication you need an EventAggregator:
//Simplest EventAggregator
public static class DumbAggregator
{
public static void BroadCast(string message)
{
if (OnMessageTransmitted != null)
OnMessageTransmitted(message);
}
public static Action<string> OnMessageTransmitted;
}
Usage:
public class MySender
{
public void SendMessage()
{
DumbAggregator.BroadCast("Hello There!");
}
}
public class MySubscriber
{
public MySubscriber()
{
DumbAggregator.OnMessageTransmitted += OnMessageReceived;
}
private void OnMessageReceived(string message)
{
MessageBox.Show("I Received a Message! - " + message);
}
}
And if you don't like Child ViewModels, you can put everything inside a single ViewModel, and have some DataTriggers
or something to dynamically change views, however a Parent - Children ViewModel approach is much cleaner IMO.
来源:https://stackoverflow.com/questions/19190942/mvvm-child-models-and-navigation-and-beer