目前在我的应用程序中,我使用func / lambda方法显示消息框,如下面的URL中所述:
要传递消息框文本和标题不是问题,但我还想传递图像框图像和图像框类型(是/否等)。这些是WPF枚举。目前我写了一些方法将这些枚举转换为非WPF(自制)枚举,但复制每个值感觉有点乏味。
在ViewModel中使用WPF枚举是否可以接受? (我猜不会)。如果没有,我如何阻止它们被使用并仍然在ViewModel中选择它们?
答案 0 :(得分:3)
我对你的术语ModelView和ViewModel略感混淆。使用MVVM,只有模型,视图和视图模型。
那篇文章讨论的是抽象消息框,以便在等待用户交互时可以在不阻塞构建服务器的情况下运行单元测试。
该实现使用Func
委托,但您可以使用界面轻松完成此操作。然后一种方法是创建自己的枚举,然后将它们转换为接口的MessageBox实现。
E.g。
public enum ConfirmationResult
{
Yes,
No,
Cancel
..etc
}
public enum ConfirmationType
{
YesNo,
OkCancel
..etc
}
public interface IConfirmation
{
ConfirmationResult ShowConfirmation(string message, ConfirmationType confirmationType)
}
public class MessageBoxConfirmation : IConfirmation
{
ConfirmationResult ShowConfirmation(string message, ConfirmationType confirmationType)
{
// convert ConfirmationType into MessageBox type here
// MessageBox.Show(...)
// convert result to ConfirmationResult type
}
}
然后,您的视图模型将IConfirmation作为依赖项(例如,在其构造函数中),并且在单元测试中,您可以将IConfirmation接口存根为始终从ShowConfirmation方法返回特定结果。
您还可以重载ShowConfirmation方法,为图像,窗口标题等提供选项。