MVVM - calling UI-logic in code behind from ViewModel

*爱你&永不变心* 提交于 2019-12-10 20:02:22

问题


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:


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.



来源:https://stackoverflow.com/questions/21330409/mvvm-calling-ui-logic-in-code-behind-from-viewmodel

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