MVVM Child models and Navigation and beer

后端 未结 1 1558
北荒
北荒 2021-01-03 08:51

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

1条回答
  •  时光说笑
    2021-01-03 09:15

    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 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.

    0 讨论(0)
提交回复
热议问题