MVVM- View Model-View Model Communications

后端 未结 4 622
我在风中等你
我在风中等你 2020-12-14 03:37

How do I go about having two view models communicate with one another using MVVM Light. I know how to use the messenger class and register etc.. Here is my Scenario

相关标签:
4条回答
  • 2020-12-14 04:07

    May be you can use sur Mediator pattern V2 Made by Josh Smith & Marlon Grech.

    Check out the Messenger class V2 in MVVM Foundation library, or directly on Marlon Grech blog

    0 讨论(0)
  • 2020-12-14 04:19

    A common pattern for this style of problem is Mediator (a class that both view models reference and can be used to pass messages between the two).

    The Mediator class has since been moved to the Cinch WPF/SL MVVM Framework, which appears to still be actively developed/supported.

    The pattern I prefer is the Event Aggregator, an example can be found in the Prism framework. In this pattern different view models subscribe to events from the aggregator and others publish events.

    Hope this helps

    0 讨论(0)
  • 2020-12-14 04:23

    I second Nigel's suggestion of using the Mediator, take a look at Josh Smith's blog and his implementation of this:

    http://joshsmithonwpf.wordpress.com/?s=mediator

    At the bottom you can download the Mediator Prototype and Demo, just remember to rename it from .doc to a .zip.

    Hope this helps...

    0 讨论(0)
  • 2020-12-14 04:27

    One thing you can try out is try to implement Dependency Inversion. Define an interface with some actions/contracts. Implement that interface on MainviewModel. Pass that interface as member variable to SettingsViewModel. So whenever settings view model has to notify something to main, it will use that interface. And additionally, other view models can use same strategy.

    public interface IMessenger
        {
          void NotifyAction();
        }

    public class MainViewModel:InotifyProprtyChanged,IMessenger
    {
     public void NotifyAction()
    {
    }
    }
    
    public class SettingsViewModel:INotifyPropertyChanged
    {
      public IMessenger Messenger{get;set;}
    
      public void SomeCommandExecutor()
      {
        if(Messenger!=null)
         {
           Messenger.NotifyAction();    
         }
    
      }
    }
    

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