[英]What is the best way to deal with dialogs in a ViewModel?
跟進 IDialogService 方法:
System.Windows.MessageBoxResult
枚舉怎么樣? 將其保留在接口之外並僅將其包含在實現中是更好的方法嗎?
我為System.Windows.MessageBoxResult
枚舉選擇的方法:
我在 IDialogInterface 旁邊添加了一個枚舉,涵蓋 Yes、NO、Ok、Cancel:
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);
}
}
初始問題:
我正在努力將所有命令從 my.asmx.cs 文件移動到某些應用程序的主要 window 的 ViewModel。
現在我必須弄清楚如何處理要求用戶確認的命令。
現在,我將在我的 ViewModel 中吸收必要的類型以直接啟動我的對話框。 我很確定這不是最好或最干凈的方法。
我發現這篇文章采用了一種有趣且更簡潔的方法。 它使用 IDialogService 接口:
public interface IDialogService
{
int Width { get; set; }
int Height { get; set; }
void Show(string title, string message, Action<DialogResult> onClosedCallback);
}
我還發現這篇 文章看起來更好,因為它在嘗試使用之前檢查 IDialogInterface 是否為 null:
private void PerformAddNewCustomer()
{
CustomerList.Add(new Customer { Name = "Name" + i });
i++;
if (dialogService != null)
{
dialogService.Show("Customed added");
}
}
這是將對話框與 ViewModel 分開的最佳方法,還是有更好的方法?
我會說您發布的鏈接中的方法是一個很好的方法,而且非常普遍(來源:我正在查看 web 上的代碼;))。 它使用起來相當簡單,它通過在單元測試中使用虛擬服務使對話框可測試,並且簡化了重構對話框的過程。
就我個人而言,我的DialogService
方法簽名采用Tuple<string, Action>
,我基於它創建對話窗口的按鈕。 它允許ViewModel
從對話框 windows 中請求一些特殊功能,而不必在每次我的需求不僅僅是一個Ok
或YesNo
消息框時向我的服務添加新方法(雖然我確實將這些方法作為自己的方法以方便采用)。
所以這是一個可靠的方法,在這一點上我不認為你會找到更好的東西,只有你可能更喜歡的東西。
您找到的文章是在 MVVM 中處理對話框 windows 的好方法,它確實可以重用,並且使用 DI 可以很容易地在您的視圖中使用。
我確實使用了一些不同的東西,大部分時間我使用 MVVM light 工具包,它有一個信使,我用信使向一個單獨的 class 發送消息,然后它為我打開了我想顯示的對話框,結果是回復消息,以便我可以根據用戶的選擇采取行動。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.