一个由SO答案实现这一目标解耦视图模型的知识有关View是通过粘贴在这里他的代码中使用回答的行动代表通过Merthere
,万一链路中断。
class MyCodeBehind
{
public MyCodeBehind()
{
Action action = new Action(()=> this.SomeMethodIWantToCall());
var myVM = new MyVM(action); // This is your ViewModel
this.DataContext = myVM;
}
private void SomeMethodIWantToCall(){...}
}
class MyVM
{
private Action action;
public MyVM(Action someAction)
{
this.action = someAction;
}
private void SomeMethodInVM()
{
this.action(); // Calls the method SomeMethodIWantToCall() in your code behind
}
}
来源
2014-10-08 14:42:30
Sai
我明白你来自哪里并相信我,我曾考虑过这一点。但是有一段时间你确实需要调用一个方法。例如,用户控件上的方法可能会暴露,并且我可能没有用户控件的源代码,所以我无法修改它以适应我的情况。 – 2010-09-14 00:08:36
虽然对于这个建议+1,但你是对的,ViewModel不应该有视图的知识。 – 2010-09-14 00:16:16
在这种情况下,可能会转到隐藏代码? – Robaticus 2010-09-14 00:27:04