从ViewModel调用View的CodeBehind中的方法吗? [英] Calling a Method in View's CodeBehind from ViewModel?

查看:59
本文介绍了从ViewModel调用View的CodeBehind中的方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的View背后的代码中有一个方法(此方法对UI有所帮助).

I have a method within the code behind of my View (this method does something to my UI).

无论如何,我想从ViewModel触发此方法.该怎么办?

Anyway, I'd like to trigger this method from my ViewModel. How could this be done?

推荐答案

我(也许还有其他?)使用MVVM的困难是要了解一个简单的东西: View知道ViewModel .我使用的是绑定和命令,但是它们在xaml中很简单.由于在运行时进行安全解析(安全意味着您可以输入错误,但软件不会崩溃),这使得视图与视图模型分离(至少在编译时).而且我一直在寻找解决方案,以保持这种脱钩,例如行为.

My (and maybe others?) difficulty with MVVM was to understand a simple thing: View knows about ViewModel. I was using bindings and commands, but they are simple strings in xaml. Because of safe resolving at run-time (safe means you can do a typo, but software will not crash) this makes view decoupled from view-model (at compile time at least). And I was always looking for solution to keep this decoupling, to example, behaviors.

事实是,您可以直接访问视图模型,通常是窗口/用户控件的DataContext:

Truth is, you can get access directly to view model, which is typically a DataContext of window/user control:

var vm = (MyViewModel)this.DataContext;

知道,使用事件可能是从视图模型调用视图方法的最佳方法,因为视图模型不知道是否存在订阅者,所以它只是触发该事件和事件可以由视图或其他视图模型使用. /p>

Knowing that, using events probably the best way to call view method from view model, because view model don't know if there is subscriber, it just firing that event and event can be used by view or another view model.

// define in the view model
public delegate void MyEventAction(string someParameter, ...);
public event MyEventAction MyEvent;

// rise event when you need to
MyEvent?.Invoke("123", ...);

// in the view
var vm = (MyViewModel)DataContext;
vm.MyEvent += (someParameter, ...) => ... // do something

这篇关于从ViewModel调用View的CodeBehind中的方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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