MVVM - 在ViewModel中的代码中调用UI逻辑 [英] MVVM - calling UI-logic in code behind from ViewModel

查看:395
本文介绍了MVVM - 在ViewModel中的代码中调用UI逻辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一些使用MVVM模式的.Net XAML应用程序。
根据MVVM,我将我的应用程序逻辑保留在VM中,并在Code Behind中执行与UI相关的操作。
但是我需要在Code Behind中执行一些与UI相关的代码,以响应VM中的某些逻辑。



示例:
我需要显示当登录操作失败时出现错误消息(在我的情况下,定制烤面包通知)。登录操作驻留在虚拟机中,但是我不能在虚拟机中使用任何特定于UI的类,所以我在虚拟机中进行了一个事件,并在代码背后进行了一些UI界面。



是否违反MVVM模式?如果是,那么如何解决我的情况?

解决方案

在MVVM模式中,View和ViewModel之间的理想沟通通过 Mediator ,以避免硬拷贝从VM查看。有一个调解员,


  1. 查看可以订阅某些类型的消息。

  2. 然后VM发送

  3. 收到后,View可以通过执行某些用户界面进行响应根据消息的逻辑

上面的CodeProject链接显示了如何实现一个调解器类。但是,我建议您使用流行的MVVM框架,因为您会发现它具有Mediator实现和许多其他可用于MVVM的工具开箱即用。


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?

解决方案

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.

这篇关于MVVM - 在ViewModel中的代码中调用UI逻辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆