MVVM:如何从视图模型调用视图方法? [英] MVVM: How to call method on view from view model?

查看:57
本文介绍了MVVM:如何从视图模型调用视图方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 MVVM 还很陌生,所以对于可能很简单的问题很抱歉.但是,我无法理解 MVVVM 中的哪种机制(如果有任何后果,我将使用 MVVMLight)来对以下简单场景进行编程:

I am quite new to MVVM, so sorry for probably simple question. However, I can not understand which mechanism from MVVVM (I am using MVVMLight if that is of any consequence) to use in order to program the simple following scenario:

我有文本框 TB,用户可以在其中填写 URL.比我有一个按钮 B 和 webview WV.如果用户单击按钮,应用程序应从 TB 中获取文本并将其显示在 WV 中.

I have textbox TB, where user can fill in URL. Than I have a button B and webview WV. If user clicks on button, the app should take the text from TB and display it in the WV.

我知道我可以在 viewmodel 中创建一个属性并将其绑定到 TB.Text.我可能也明白我应该创建将从按钮 B 中绑定的命令,但是我应该在命令中做什么.当我没有参考 WV 时,我如何调用 WV.navigate(url).这应该通过一些我没有正确理解的行为来解决吗?这样做的最佳方法是什么?

I knwo that I can create a property in viewmodel and bound it to TB.Text. I understand probably also that I should create command which will be boudn from button B, but what should I do in the command. How I can call WV.navigate(url), when I do not have reference to WV. Should this be solved by something, which I did not grasp correctly like behaviours? What is the best way to do this?

推荐答案

你应该使用信使模式来解决这个问题:

You should use the messenger pattern for this problem:

这个想法是,视图可以注册特定的消息类(在这种情况下,例如一个自己的 NavigateToUriMessage 类),并且视图模型可以将这个消息类的实例发送给监听消息的任何人消息类型.在命令实现中,您只需发送此消息,视图接收消息并更改 Web 视图的 URI.

The idea is that the view can register for specific message classes (in this case for example an own NavigateToUriMessage class) and the view model can send an instance of this message class to whoever listens to the message type. In the command implementation you simply send this message, the view receives the message and changes the URI of the web view.

顺便说一句:这种信使模式的想法是,您可以更好地编写单元测试并将视图模型用于其他平台(对消息的反应可能不同).

BTW: The idea of this messenger pattern is that you can better write Unit Tests and use the view model for other platforms (where the reaction to the message may differ).

这篇关于MVVM:如何从视图模型调用视图方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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