3

I'm working on some .Net XAML application using MVVM pattern. According to MVVM I keep my app logic in VM and in Code Behind I do UI-related actions. But I need to execute some UI-related code in Code Behind in respond to some logic in VM.

Example: I need to show an error message (custom toast notification in my case) when login operation failed. Login operation resides in VM, but I can't use any UI-specific classes in my VM, so I made an event in VM and hooking up to in in Code Behind, doing UI stuff.

Is it a violation of MVVM pattern? If yes, then how to solve my case?

1 Answers1

4

Ideally communication between View and ViewModel in MVVM pattern done through Mediator to avoid hard-referencing View from VM. Having a mediator,

  1. View can subscribe to certain type of message.
  2. Then VM send the message to mediator,
  3. mediator broadcast the message, so all party that subscribed will get it.
  4. Upon receiving, View can respond by executing certain UI logic according to the message

The CodeProject link above shows how to implement a mediator class. But I will suggest to use a popular MVVM framework since you'll find it has Mediator implementation and many other tools for MVVM available out-of-the-box.

Community
  • 1
  • 1
har07
  • 88,338
  • 12
  • 84
  • 137
  • if you chose MVVMLight framework, you can see how simple subscribe and sending message through Messenger (class name for mediator implementation in MVVMlight) in [this post](http://stackoverflow.com/q/16993918/2998271) – har07 Jan 24 '14 at 12:23
  • Thx, I'll read about mediator, but in case of using VM events there is no hard links to View. VM doesn't care who is exactly hooked up to the event, so event mechanism is some sort of simple built in mediator here? – Anton Korzhenevskiy Jan 25 '14 at 10:35
  • sorry fixed the link. – har07 Jan 25 '14 at 10:55
  • So far I see Mediator is more common and save approach. For simple application using VM event approach maybe acceptable and save. But for more complex scenario we should be careful, because that approach will prevent View from being garbage-collected since there is reference to View from VM event. In case of using Mediator, it won't prevent subscribing parties from being garbage-collected [[Reference](http://www.codeproject.com/Articles/173630/MVVM-sharp-Episode-2)] – har07 Jan 25 '14 at 11:50
  • another advantage is, Mediator also applicable for VM-to-VM communication in case we want to avoid having reference from one VM to another. In short Mediator help us to avoid having reference from one class to another but still enable us to communicate between them *IN SAVE, WEAK-REFERENCE WAY* – har07 Jan 25 '14 at 12:00