MVVM Child models and Navigation and beer

爱⌒轻易说出口 提交于 2019-12-30 05:19:10

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!