MVVM: How to call method on view from view model?

天涯浪子 提交于 2019-12-11 09:58:46

问题


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:

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.

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?


回答1:


You should use the messenger pattern for this problem:

  • http://msdn.microsoft.com/en-us/magazine/dn745866.aspx
  • http://www.codeproject.com/Tips/696340/Thinking-in-MVVMLight-Messenger
  • http://mytoolkit.codeplex.com/wikipage?title=Messenger

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).




回答2:


Another way is to create an attached property for the WebView class where you can bind an Uri property to. The attached property calls Navigate when the bound value changes.

Check out this blog:

  • http://blogs.msdn.com/b/wsdevsol/archive/2013/09/26/binding-html-to-a-webview-with-attached-properties.aspx


来源:https://stackoverflow.com/questions/25310867/mvvm-how-to-call-method-on-view-from-view-model

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