关于这个主题有很多答案,从创建自定义类到使用第三方库。如果您想要具有漂亮视觉效果的酷炫弹出窗口,我会说使用第三方库。
但是,如果您只想为您的 WPF 应用程序使用微软的常规消息框,这里是一个 MVVM/单元测试友好的实现:
最初我以为我会从消息框继承并用接口包装它,但由于消息框没有公共构造函数,我不能,所以这里是“简单”的解决方案:
在visual studio中反编译消息框,你可以看到所有的方法重载,我检查了我想要的,然后创建了一个新类并添加了方法,用接口和ta-da包装了它!现在您可以使用ninject绑定接口和类,注入它并使用Moq进行单元测试等
创建一个接口(只添加了一些重载,因为我不需要全部):
public interface IMessageBox
{
/// <summary>Displays a message box that has a message, title bar caption, and button; and that returns a result.</summary>
MessageBoxResult Show(string messageBoxText, string caption, MessageBoxButton button);
/// <summary>Displays a message box that has a message, title bar caption, button, and icon; and that returns a result.</summary>
MessageBoxResult Show(string messageBoxText, string caption, MessageBoxButton button, MessageBoxImage icon);
/// <summary>Displays a message box that has a message and title bar caption; and that returns a result.</summary>
MessageBoxResult Show(string messageBoxText, string caption);
}
然后我们有将从它继承的类:
public class MessageBoxHelper : IMessageBox
{
/// <summary>Displays a message box that has a message, title bar caption, button, and icon; and that returns a result.</summary>
public MessageBoxResult Show(string messageBoxText, string caption, MessageBoxButton button,
MessageBoxImage icon)
{
return MessageBox.Show(messageBoxText, caption, button, icon, MessageBoxResult.None,
MessageBoxOptions.None);
}
/// <summary>Displays a message box that has a message, title bar caption, and button; and that returns a result.</summary>
public MessageBoxResult Show(string messageBoxText, string caption, MessageBoxButton button)
{
return MessageBox.Show(messageBoxText, caption, button, MessageBoxImage.None, MessageBoxResult.None,
MessageBoxOptions.None);
}
/// <summary>Displays a message box that has a message and title bar caption; and that returns a result.</summary>
public MessageBoxResult Show(string messageBoxText, string caption)
{
return MessageBox.Show(messageBoxText, caption, MessageBoxButton.OK, MessageBoxImage.None,
MessageBoxResult.None, MessageBoxOptions.None);
}
/// <summary>Displays a message box that has a message and that returns a result.</summary>
public MessageBoxResult Show(string messageBoxText)
{
return MessageBox.Show(messageBoxText, string.Empty, MessageBoxButton.OK, MessageBoxImage.None,
MessageBoxResult.None, MessageBoxOptions.None);
}
}
现在只需在注入等时使用它,然后繁荣你有一个脆弱的抽象可以解决问题......这很好,取决于你将在哪里使用它。我的案例是一个简单的应用程序,只打算做一些事情,所以没有必要设计一个解决方案。希望这可以帮助某人。