如何从其他视图模型中调用主视图模型中的函数?我的节目由一个TreeView和两个contentPresenters地面组成。mainWindow,TreeView和每个contentPresenter都有自己的viewModels。我想调用一个函数在mainWindowViewModel从TreeViewViewModel。我需要这样做因为mainWindowViewModel控件显示的内容contentPresenters,我想手动更新显示。我猜我会做这样的事......TreeViewViewModel:public class TreeViewViewModel{
//Do I need to declare the MainWindowVM?
public TreeViewViewModel() { ... }
private void function()
{
//Command that affects display
//Manually call function in MainWindowVM to refresh View
}}我试图通过使用来访问MainWindowVM来自TreeViewViewModel:public MainWindowViewModel ViewModel { get { return DataContext as MainWindowViewModel; } }但它没有多大意义。因为MWVM不是DataContext的TreeViewViewModel。
2 回答
幕布斯6054654
TA贡献1876条经验 获得超7个赞
最简单的方法是将方法传递给Action
子视图模型的构造函数。
public class ParentViewModel{ ChildViewModel childViewModel; public ParentViewModel() { childViewModel = new ChildViewModel(ActionMethod); } private void ActionMethod() { Console.WriteLine("Parent method executed"); }}public class ChildViewModel{ private readonly Action parentAction; public ChildViewModel(Action parentAction) { this.parentAction = parentAction; CallParentAction(); } public void CallParentAction() { parentAction.Invoke(); }}
- 2 回答
- 0 关注
- 428 浏览
添加回答
举报
0/150
提交
取消