gpt4 book ai didi

c# - 如何在 ModelView 中防止 WPF 枚举

转载 作者:行者123 更新时间:2023-12-03 11:00:31 25 4
gpt4 key购买 nike

目前在我的应用程序中,我使用 func/lambda 方法显示消息框,如下面的 url 中所述:

http://www.deanchalk.me.uk/post/WPF-MVVM-e28093-Simple-e28098MessageBoxShowe28099-With-Action-Func.aspx

传递消息框文本和标题不是问题,但是我还想传递图像框图像和图像框类型(是/否等)。这些是 WPF 枚举。目前,我编写了一些方法将这些枚举转换为非 WPF(自己制作的)枚举,但复制每个值感觉有点乏味。

在 ViewModel 中使用 WPF 枚举是否可以接受? (我猜不会)。如果没有,我怎样才能防止它们被使用并仍然在 ViewModel 中选择它们?

最佳答案

我对您的术语 ModelView 和 ViewModel 感到有些困惑。使用 MVVM,只有模型、 View 和 View 模型。

那篇文章正在讨论抽象消息框,以便您可以在等待用户交互时运行单元测试而不会阻塞构建服务器。

该实现使用 Func委托(delegate),但您可以使用接口(interface)轻松完成此操作。然后一种方法是创建您自己的枚举,然后将它们转换为接口(interface)的 MessageBox 实现。

例如。

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
}
}

然后,您的 View 模型将 IConfirmation 作为依赖项(例如在其构造函数中),并且在单元测试中,您可以 stub IConfirmation 接口(interface)以始终从 ShowConfirmation 方法返回特定结果。

您还可以重载 ShowConfirmation 方法以提供图像、窗口标题等选项。

关于c# - 如何在 ModelView 中防止 WPF 枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9225703/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com