不建议在MVVM应用程序中使用MessageBox? [英] MessageBox is not recommended in MVVM applications?
问题描述
当我问到如何在MVVM中实现对话框时,有人建议我阅读此线程:
When I asked about how to implement a dialog in MVVM someone advised me to read this thread:
在视图模型中,该对话框被称为这样:
In the view model, the dialog is called in this way:
var dialog = new DialogViewmodel();
var result = _dialogservice.ShowDialog("My Dialog", dialog);
if(result.HasValue && result.Value)
{
//accept true
}
else
{
//Cancel or false
}
但这与使用messageBox不同吗
But is this different than using a messageBox in this way?
DialogResult result = MessageBox.Show("Hello");
if(result == DialgoResult-OK)
{
//accept true
}
else
{
//Cancel or false
}
在第二种情况下,我使用MessageBox代替自定义对话框,所以我看不出有什么区别。
In this second case, I use MessageBox instead of the custom dialog, so I don't see any difference.
无论如何,在许多情况下,我读到在MVVM应用程序中使用MessageBox是一个坏主意,因为它会破坏MVVM模式。但是,如果确实如此,我看不到第一种解决方案不会破坏MVVM模式,而第二种解决方案不会破坏它。
Anyway, in many cases I have read that to use a MessageBox in MVVM application it is a bad idea because it breaks the MVVM pattern. But really if this is true, I don't see how the first solution doesn't break the MVVM pattern and the second one breaks it.
推荐答案
MVVM模式的基本思想是关注点分离。视图模型不应该知道如何处理或显示对话框。为什么?以下是一些原因:
The basic idea of the MVVM pattern is the separation of concerns. The View Model should not know how to handle or present a dialog. Why? Here are some reasons:
- 测试视图模型:不需要对话框(假设您一直需要单击对话框)
- 创建GUI应用程序的控制台应用程序(对话框应在控制台中显示,而不是作为弹出框显示)
- 需要更改对话框的设计(假设您需要更改所有MessageBox调用)
- ...
- Testing your View Model: No dialogs are desired (Imagine you need to click dialogs all the time)
- Creating a console application of a GUI application (The dialogs should be shown in console not as popup boxes)
- It is required to change the design of your dialogs (Imagine you need to change all MessageBox calls)
- ...
解决方案:
通过为对话框实现定义良好的界面来使用依赖项注入。您可以在此答案。
结果:
调用 _dialogservice.ShowDialog
可能只是 MessageBox.Show
的包装,但也可能是控制台应用程序或调试日志中控制台中的某些对话框。在测试期间。因此,代码与任何演示文稿都完全分开。
Result:
Calling _dialogservice.ShowDialog
is maybe only a wrapper of MessageBox.Show
but could also be a some dialog in a console in a console application or debug log during testing. So the code is well separated of any presentation.
这篇关于不建议在MVVM应用程序中使用MessageBox?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!