码迷,mamicode.com
首页 > Windows程序 > 详细

WPF 高级篇 MVVM (MVVMlight) 依赖注入使用Messagebox

时间:2019-12-21 09:28:15      阅读:538      评论:0      收藏:0      [点我收藏+]

标签:rgs   key   cancel   函数   ioc   eve   question   成功   lang   

原文:WPF 高级篇 MVVM (MVVMlight) 依赖注入使用Messagebox

MVVMlight 实现依赖注入 把弹框功能 和接口功能注入到各个插件中

使用依赖注入 先把所有的ViewModel都注册到到容器中 MVVMlight SimpleIoc 来实现注册

  1. public ViewModelLocator()
  2. {
  3. SimpleIoc.Default.Register<MainViewModel>();
  4. SimpleIoc.Default.Register<EditBookViewModel>();
  5. SimpleIoc.Default.Register<IDialogService, DialogService>();
  6. }
  7. private MainViewModel mainViewModel ;
  8. public MainViewModel MainViewModel
  9. {
  10. get { return mainViewModel = SimpleIoc.Default.GetInstance<MainViewModel>(Guid.NewGuid().ToString()); }
  11. set { mainViewModel = value; }
  12. }
  13. private EditBookViewModel editBookViewModel ;
  14. public EditBookViewModel EditBookViewModel
  15. {
  16. get { return editBookViewModel = SimpleIoc.Default.GetInstance<EditBookViewModel>(Guid.NewGuid().ToString()); }
  17. set { editBookViewModel = value; }
  18. }

Message 接口

  1. public interface IDialogService
  2. {
  3. void ShowMessage(string message, string title = "提示");
  4. bool Confirm(string message, string title = "询问");
  5. }

实现类

  1. public class DialogService:IDialogService
  2. {
  3. public void ShowMessage(string message, string title = "提示")
  4. {
  5. MessageBox.Show(message, title, MessageBoxButton.OK, MessageBoxImage.Information);
  6. }
  7. public bool Confirm(string message, string title = "询问")
  8. {
  9. var result = MessageBox.Show(message, title, MessageBoxButton.OKCancel, MessageBoxImage.Question);
  10. if (result == MessageBoxResult.OK)
  11. {
  12. return true;
  13. }
  14. else
  15. {
  16. return false;
  17. }
  18. }
  19. }

在每一个View Model 的构造函数里  定义接口对象

 

  1. public EditBookViewModel(IDialogService dialogService)
  2. {
  3. DialogService = dialogService;
  4. }
  5. private IDialogService dialogService;
  6. public IDialogService DialogService
  7. {
  8. get { return dialogService; }
  9. set { dialogService = value; }
  10. }

 

并使用方法

  DialogService.ShowMessage(EditBookArgs.IsEdit ? "编辑成功" : "新增成功");

 

WPF 高级篇 MVVM (MVVMlight) 依赖注入使用Messagebox

标签:rgs   key   cancel   函数   ioc   eve   question   成功   lang   

原文地址:https://www.cnblogs.com/lonelyxmas/p/12075815.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!