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

标签 c# wpf mvvm viewmodel

我的程序由一个 TreeView 和两个位于地面的 contentPresenters 组成。 mainWindow、TreeView 和每个 contentPresenter 都有自己的 viewModel。

我想从 TreeViewModel 调用 mainWindowViewModel 中的函数。

我需要这样做,因为 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
     }
}

我尝试通过以下方式从 TreeViewViewModel 访问 MainWindowVM:

public MainWindowViewModel ViewModel { get { return DataContext as MainWindowViewModel; } }

但意义不大。因为 MWVM 不是 TreeViewViewModelDataContext

最佳答案

The delegate method used in this and the linked answer can be used in any parent-child relationship and in either direction. That includes from a child view model to a parent view model, a Window code behind to the code behind of a child Window, or even pure data relationships without any UI involved. You can find out more about using delegate objects from the Delegates (C# Programming Guide) page on MSDN.

我今天早些时候刚刚回答了一个类似的问题。如果你看一下 Passing parameters between viewmodels帖子,您会看到答案涉及使用 delegate 对象。您可以简单地将这些委托(delegate)(来自答案)替换为您的方法,它将以相同的方式工作。

如果您有任何问题,请告诉我。


更新>>>

是的,抱歉,我完全忘记了您想要调用方法...我今晚写了太多帖子。所以仍然使用其他帖子中的示例,只需在 ParameterViewModel_OnParameterChange 处理程序中调用您的方法:

public void ParameterViewModel_OnParameterChange(string parameter)
{
    // Call your method here
}

delegate 视为返回父 View 模型的路径...这就像引发一个名为 ReadyForYouToCallMethodNow 的事件。 事实上,您甚至不需要需要有一个输入参数。您可以像这样定义您的委托(delegate):

public delegate void ReadyForUpdate();

public ReadyForUpdate OnReadyForUpdate { get; set; }

然后在父 View 模型中(像其他示例一样附加处理程序之后):

public void ChildViewModel_OnReadyForUpdate()
{
    // Call your method here
    UpdateDisplay();
}

因为您有多个 subview 模型,您可以在它们都可以访问的另一个类中定义 delegate。如果您还有其他问题,请告诉我。


更新 2 >>>

再次阅读您的最后一条评论后,我想到了一种更简单的方法,可能实现您想要的……至少,如果我理解正确的话。您可以Bind 直接从您的 subview 到您的父 View 模型。例如,这将允许您将 subview 中的一个 Button.Command 属性Bind 到父 View 模型中的一个 ICommand 属性:

TreeViewView 中:

<Button Content="Click Me" Command="{Binding DataContext.ParentCommand, 
RelativeSource={RelativeSource AncestorType={x:Type MainWindow}}}" />

这当然假设所讨论的父 View 模型的一个实例被设置为 MainWindowDataContext

关于c# - 如何从其他 View 模型调用主视图模型中的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19522202/

相关文章:

c# - WPF BIND 通过位图资源动态绑定(bind)图像

.net - 样式不更新

C# 创建类的实例并在字符串中按名称设置属性

c# - 如何将文本框对象绑定(bind)到 ViewModel

c# - 是否可以告诉 Visual Studio 不要将源文件视为 "component"?

c# - 如何从MobileServiceUser获取用户名、电子邮件等?

c# - WPF如何使文本框在按下回车后失去焦点

c# - 搜索后覆盖记录 -MVVM WPF

C# 动态引用集合对象?

c# - ASP.NET Identity 2 Invalidate Identity难点