轻量级MVVM框架Stylet介绍:(7) MessageBox

为方便测试,Stylet实现了MessageBox的克隆版本,几乎与WPF原生的一样。

使用

要使用MessageBox,只需要在IWindowManager中调用ShowMessageBox方法:


public MyViewModel
{
   private readonly IWindowManager windowManager;
 
   public MyViewModel(IWindowManager windowManager)
   {
      this.windowManager = windowManager;
   }
 
   public void ShowMessagebox()
   {
      var result = this.windowManager.ShowMessageBox("Hello");
   }
}

定制MessageBox

Stylet 的 MessageBox 是作为 ViewModel 实现的MessageBoxViewModel,以及其相应的 View,MessageBoxView。ViewModel 实现一个接口 IMessageBoxViewModel,ShowMessageBox()方法使用此接口来检索 ViewModel 的实例。

因此,您可以编写实现lMessageBoxView 的 ViewModel 并将其注册到 IoC 容器中,从而为您提供自己的自定义实现。然后,通过调用ShowMessageBox()来使用这个新的MessageBox。

定制按钮文本

修改MessageBoxViewModel.ButtonLabels,这是一个字典,如下例所示:

MessageBoxViewModel.ButtonLabels[MessageBoxResult.No] = "No, thanks";
 
this.windowManager.ShowMessageBox("Do you want breakfast?", 
                                   buttons: MessageBoxButton.YesNo, 
                                   buttonLabels: new Dictionary<MessageBoxResult, string>()
        {
            { MessageBoxResult.Yes, "Yes please!" },
        });
 
// Will display a MessageBox with the buttons "Yes please!" and "No, thanks"
  • MessageBoxViewModel.ButtonToResults,字典变量,定制对话框同时显示按钮的类型;
  • MessageBoxViewModel.IconMapping,字典变量,定制对话框同时显示图标的类型;为null时表示不显示任何图标;
  • MessageBoxViewModel.SoundMapping,字典变量,定制对话框播放声音的类型
  • IWindowManager.ShowMessageBox()有一些参数可用于指定FlowDirection和 TextAlignment。如果未指定这些,则使用默认值和。如果您愿意,也可以更改这些默认值。
原文地址:https://www.cnblogs.com/qouoww/p/15797191.html