在ViewModel中处理对话框的最佳方法是什么?

4

在IDialogService方法的基础上:

那么对于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中吸收必要的类型,以直接启动我的对话框。我很确定这不是最好或最干净的方法。

我发现这篇文章使用了一个IDialogService接口,提供了一种有趣而且更为简洁的方法。

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

我还发现了这篇文章,它似乎更好,因为它在尝试使用IDialogInterface之前会检查其是否为空:

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

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

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

2个回答

1

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

就我个人而言,我的DialogService方法签名采用Tuple<string, Action>列表,我根据此创建对话框窗口的按钮。这允许ViewModel从对话框窗口请求一些特殊功能,而无需每次需要更多于OkYesNo消息框时都向我的服务添加新方法(尽管我确实有这些方法以便使用)。

因此,这是一个可靠的方法,目前我认为你不会找到更好的方法,只有你可能更喜欢的方法。


0
你找到的文章是处理MVVM对话框窗口的好方法,非常可重用,在 DI 的帮助下在你的视图中使用也很容易。
我使用了不同的东西,大多数时候我使用 MVVM light 工具包,它有一个信使,我使用信使发送消息到一个独立的类,然后它为我打开了想要显示的对话框,结果被传回,这样我就可以根据用户的选择进行操作。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接