-1

当我们使用 MVVM 时,我们被告知要避免在 ViewModel 中使用 System.Windows.MessageBox,我猜这是因为它不利于我们的测试。这是真的吗?

使用 Prism NotificationRequest,我们可以与用户交流,但它比简单的 MessageBox 稍微复杂一些。

另一种方法是使用 Xceed Wpf Toolkit MessageBox,它比 Prism NotificationRequest 更简单。

我的问题是:它们都等价吗?我们可以以 MVVM 方式使用它们中的任何一个吗?如果否,我们什么时候需要使用 NotificationRequest,什么时候可以使用 Xceed MessageBox?

谢谢

4

1 回答 1

1

如果您MessageBox.Show()从可以在测试时用模拟替换的服务调用,那很好。

毕竟,您不希望在运行视图模型单元测试时弹出一个消息框......

例子:

public interface IMessageBoxService
{
    ClickedButten ShowMessageBox( string message, Buttons buttons );
}

internal class SomeViewModel
{
    public SomeViewModel( IMessageBoxService messageBoxService )
    {
        _messageBoxService = messageBoxService;
    }

    public void SomeMethodThatNeedsAMessageBox()
    {
        var theClickedButton = _messageBoxService.ShowMessageBox( "Click me!", Buttons.Ok | Buttons.Cancel );
        // react to the click...
    }
}

internal class SystemMessageBoxService : IMessageBoxService
{
    public ClickedButten ShowMessageBox( string message, Buttons buttons )
    {
        // adapt parameters...
        MessageBox.Show(...);
        // adapt result...
    }
}

internal class XceedMessageBoxService : IMessageBoxService
{
    public ClickedButten ShowMessageBox( string message, Buttons buttons )
    {
        // adapt parameters...
        Xceed.ShowMessageBox(...);
        // adapt result...
    }
}

现在只需绑定您要使用的服务(甚至可以在运行时确定),并在测试时注入模拟。

于 2017-03-11T20:19:54.340 回答