c# - 在 ViewModel 中处理对话框的最佳方式是什么?

标签 c# wpf mvvm

IDialogService 方法的跟进:

System.Windows.MessageBoxResult 枚举怎么样?将其保留在接口(interface)之外并仅在实现中涉及它是更好的方法吗?

我为 System.Windows.MessageBoxResult 枚举 选择的方法:

我在 IDialogInterface 旁边添加了一个枚举,涵盖是、否、确定、取消:

namespace Foo.Bar.Dialogs
{
    public enum DialogResult { Ok, Yes, No, Cancel }

    public interface IDialogService
    {
        void ShowErrorBox(string error_message);

        DialogResult ShowQuestionBox(string question_message);

        DialogResult ShowQuestionBox(string question_message, string caption);

        DialogResult ShowQuestionBox(string question_message, string caption, bool allow_cancel);

        DialogResult ShowQuestionBox(string question_message, string caption, bool allow_cancel, bool show_as_error);

        void ShowWarningBox(string message, string caption = "");

        void ShowInformationBox(string message);

        void ShowInformationBox(string message, string caption);
    }
}

初始问题:

我正在努力将所有命令从我的 .asmx.cs 文件移动到某个应用程序主窗口的 ViewModel。

现在我必须弄清楚如何处理要求用户确认的命令。

现在 我将在我的 ViewModel 中吸收必要的类型以直接启动我的对话框。我很确定这不是执行此操作的最佳或最干净方法。

我找到了这个 article用一种有趣和更清洁的方法。它使用 IDialogService 接口(interface):

public interface IDialogService
{
    int Width { get; set; }
    int Height { get; set; }
    void Show(string title, string message, Action<DialogResult> onClosedCallback);
}

我也找到了这个article这看起来更好,因为它在尝试使用之前检查 IDialogInterface 是否为空:

private void PerformAddNewCustomer() 
{ 
    CustomerList.Add(new Customer { Name = "Name" + i }); 
    i++; 

    if (dialogService != null) 
    { 
        dialogService.Show("Customed added"); 
    } 
} 

这是将对话框与 ViewModel 分开的最佳方法,还是有更好的方法?

最佳答案

我想说您发布的链接中的方法是一个很好的方法,而且非常普遍(来源:我在网上查看代码;))。它使用起来相当简单,它通过在单元测试中使用虚拟服务使对话框可测试,并且简化了重构对话框的过程。

就个人而言,我的 DialogService方法签名采用 Tuple<string, Action> 的列表然后我基于它创建我的对话框窗口的按钮。它允许 ViewModel每次我的需求超过 Ok 时,无需向我的服务添加新方法就可以从对话框窗口中请求一些特殊功能或 YesNo消息框(虽然为了方便使用,我确实有自己的方法)。

所以这是一个可靠的方法,在这一点上我不认为你会找到更好的东西,只有你可能更喜欢的东西。

关于c# - 在 ViewModel 中处理对话框的最佳方式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10042067/

相关文章:

c# - .net 中 string.Format (".... {0}....{1}....",v1,v2) 的替代品?

c# - 窗体 : navigate TreeView in BackgroundWorker thread

c# - 在c#中实现java函数

wpf - WPF 中 VisualTreeHelper.HitTest 的问题

WPF:隔离存储文件路径太长

wpf - UI 选项卡控制调试和部署版本之间的可见性变化

c# - ASP.NET + 线程感知非托管 API

c# - WPF Infragistics XamDataGrid 窃取滚动焦点

c# - 如何使用 Unity 从 ViewModel 创建新的窗口实例?

c# - 为什么 List<T> 属性的通知不起作用