开发者

How to use Messageboxes in MVVM?

开发者 https://www.devze.com 2023-01-01 02:38 出处:网络
It seems that the XAML in MVVM pattern has difficulty to pop-up a Messageboxes. My client insists that the validation labels and colors are not good for them. They still want a messagebox. How can do

It seems that the XAML in MVVM pattern has difficulty to pop-up a Messageboxes. My client insists that the validation labels and colors are not good for them. They still want a messagebox. How can do it?

I know I can pop-up messageboxes in the view-model, but it violates the whole purpose for the view-model. I can also raise a error, and pop-up a messagebox in some exception handlers, but the messagebox is not an exce开发者_运维技巧ption. It is part of the normal program flow.

Is there a good way to do it in XAML? My client likes messageboxes. She does not care about the MVVM pattern, she never had any quality problem before using MVVM and unit test. But now, she can not even get her messageboxes, so she is not very happy.


One possibilty is to use an interface for the messagebox like

public interface IMessageBoxProvider
{
    MessageBoxResult Show(string messageBoxText, string caption, MessageBoxButton button, MessageBoxImage icon, MessageBoxResult defaultResult);

}

and a wrapper class that implements this interface and uses a normal or custom messagebox. In the viewmodel you can then use like this

private IMessageBoxProvider MessageBox { get; set; }

where MessageBox is the wrapper class. So now you have decoupled the actual messagebox and so you are able to to unit testing and what not.


Josh Smith also has a CodeProject article that might interest you here.


You can have a PopUpNotificationRequested event in your ViewModel which will be handled by the View to show message boxes. This way the logic to show the messagebox stays in the viewmodel, but is still decoupled from the view.


The ViewModel sample application of the WPF Application Framework (WAF) project shows how to show a MessageBox without violating the MVVM pattern.


I ran into this problem a few weeks ago. I came across this article (http://blog.roboblob.com/2010/01/19/modal-dialogs-with-mvvm-and-silverlight-4/) and essentially followed a very similar process for showing modal dialogs with the MVVM pattern. For testing my ViewModels simply just create a mock modal dialog service.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号