一個由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