[英]How to invoke a ViewModel method with result from View in Caliburn.Micro
In my Caliburn.Micro project I have a Window view. 在我的Caliburn.Micro项目中,我有一个Window视图。
I use some Invoke in the View to call methods of the ViewModel: 我在视图中使用一些Invoke来调用ViewModel的方法:
private void ViewEvent1(object sender, RoutedEventArgs e)
{
Caliburn.Micro.Action.Invoke(DataContext, "Event1Occured");
}
private void ViewEvent2(object sender, RoutedEventArgs e)
{
Caliburn.Micro.Action.Invoke(DataContext, "Event2Occured");
}
They work just fine. 他们工作得很好。
In my View, I have a method that closes the Window: 在我的视图中,我有一个关闭窗口的方法:
private void EventClose(object sender, RoutedEventArgs e)
{
this.DialogResult = false;
Close();
}
Unfortunately I have to check some conditions in the ViewModel before the closing takes effect. 不幸的是,在关闭生效之前,我必须检查ViewModel中的某些条件。
The problem is that Invoke return void , so I cannot call a method that returns a value. 问题是Invoke返回void ,所以我不能调用返回值的方法。
Is there an alternative for Invoke to get the result from the ViewModel's method? Invoke是否可以从ViewModel的方法获取结果?
You don't want to be doing your method calls to viewmodels from the view in that nature.. kinda breaks the ideas behind CMs abilities even for the items that you claim work. 您本质上不希望从视图中进行对视图模型的方法调用。有点儿破坏了CM功能背后的想法,即使您主张工作的项目也是如此。
as eran otzap pointed out you need use convention or Message.Attach, to call a method on the viewmodel from the view is breaking a few things, might as well not use CM in this case. 正如eran otzap指出的那样,您需要使用Convention或Message.Attach,以便从视图中调用viewmodel上的方法破坏了一些事情,在这种情况下可能不使用CM。 Some will go as far as deleting code behind files altogether, because they don't use them at all. 有些人甚至会完全删除文件后面的代码,因为它们根本不使用它们。
Secondly, if it's view related then it doesn't affect the viewmodel that is ok, but since you are calling the viewmodel the premise of SoC and MVVM are thrown out and testing becomes very difficult. 其次,如果它与视图相关,那么它不会影响正常的视图模型,但是由于您正在调用该视图模型,因此SoC和MVVM的前提被抛弃了,并且测试变得非常困难。
Invoking is bad, event passage might be slightly better but still requires some very smelly code to do it. 调用是不好的,事件传递可能会稍微好一些,但仍然需要一些非常臭的代码才能执行。
The documentation at caliburnmicro.com are pretty clear and the examples on the github repository are pretty thorough for ideals that are in place for CMs usage. caliburnmicro.com上的文档非常清楚,而github存储库上的示例对于针对CM使用的理想情况而言非常详尽。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.