【发布时间】:2016-05-06 11:23:00
【问题描述】:
本题涉及基于 PRISM 5.0 和 MVVM 模式的 WPF 应用程序。
有时当用户做出可能会产生不良或负面后果的决定时,通常会询问用户是否真的想继续下去。
例如: 一种常见的方法是用消息框询问用户,如果他真的想删除数据,删除后无法恢复。
问题是: 如果我在 ViewModel 中调用 MessageBox,ViewModel 从外部变为 untestable。
//BAD!
public class ViewModel
{
public Boolean Delete()
{
//Blocking and therefore untestable in automatic UnitTests
MsgBoxResult result = MsgBox.Show("Do you really want to delete?");
if (result == yes) {//Do stuff that deletes data here;}
}
}
一种可能性是,以不同的私有方法提出问题,该方法调用公共方法
//BETTER, BUT OK?
public class ViewModel
{
private void OnDeleteAction
{
MsgBoxResult result = MsgBox.Show("Do you really want to delete?");
if (result == yes) {Delete();}
}
public Boolean Delete()
{
//Testable from the outside again, because no blocking question
//Do stuff that deletes data here
}
我的问题:这是在 ViewModel 中询问用户的好方法还是有更优雅的方法?你能给我一个提示或链接,什么是 PRISM 5.0 最好的?
我知道,经验法则是,不要在 ViewModel 中使用任何 UI 元素,但我认为在继续之前,除了阻塞 MessageBox 或其他东西之外别无选择。
感谢您的任何提示!
【问题讨论】:
-
据我了解,不应在视图模型中编写任何与视图相关的代码,在视图端编写与逻辑相关的代码。因此,您可以在视图代码中打开消息框,并根据您在视图模型类中调用删除方法的用户选择。
-
public interface MuhMessageBox { bool AreYouCrazy(string message); }
标签: c# wpf mvvm prism blocking