如何从其他视图模型中调用主视图模型中的函数?

如何从其他视图模型中调用主视图模型中的函数?

我的节目由一个TreeView和两个contentPresenters地面组成。mainWindow,TreeView和每个contentPresenter都有自己的viewModels。

我想调用一个函数在mainWindowViewModelTreeViewViewModel

我需要这样做因为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不是DataContextTreeViewViewModel


至尊宝的传说
浏览 429回答 2
2回答

幕布斯6054654

最简单的方法是将方法传递给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();     }}
打开App,查看更多内容
随时随地看视频慕课网APP