我的程序由一个 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 不是 TreeViewViewModel
的 DataContext
。
最佳答案
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, aWindow
code behind to the code behind of a childWindow
, or even pure data relationships without any UI involved. You can find out more about usingdelegate
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 模型的一个实例被设置为 MainWindow
的 DataContext
。
关于c# - 如何从其他 View 模型调用主视图模型中的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19522202/