MVVMlight 实现依赖注入 把弹框功能 和接口功能注入到各个插件中
使用依赖注入 先把所有的ViewModel都注册到到容器中 MVVMlight SimpleIoc 来实现注册
-
-
public ViewModelLocator()
-
{
-
SimpleIoc.Default.Register<MainViewModel>();
-
SimpleIoc.Default.Register<EditBookViewModel>();
-
SimpleIoc.Default.Register<IDialogService, DialogService>();
-
}
-
-
-
private MainViewModel mainViewModel ;
-
-
public MainViewModel MainViewModel
-
{
-
get { return mainViewModel = SimpleIoc.Default.GetInstance<MainViewModel>(Guid.NewGuid().ToString()); }
-
set { mainViewModel = value; }
-
-
}
-
-
private EditBookViewModel editBookViewModel ;
-
-
public EditBookViewModel EditBookViewModel
-
{
-
get { return editBookViewModel = SimpleIoc.Default.GetInstance<EditBookViewModel>(Guid.NewGuid().ToString()); }
-
set { editBookViewModel = value; }
-
}
Message 接口
-
public interface IDialogService
-
{
-
void ShowMessage(string message, string title = "提示");
-
bool Confirm(string message, string title = "询问");
-
}
实现类
-
public class DialogService:IDialogService
-
{
-
public void ShowMessage(string message, string title = "提示")
-
{
-
MessageBox.Show(message, title, MessageBoxButton.OK, MessageBoxImage.Information);
-
}
-
-
public bool Confirm(string message, string title = "询问")
-
{
-
var result = MessageBox.Show(message, title, MessageBoxButton.OKCancel, MessageBoxImage.Question);
-
if (result == MessageBoxResult.OK)
-
{
-
return true;
-
}
-
else
-
{
-
return false;
-
}
-
}
-
}
在每一个View Model 的构造函数里 定义接口对象
-
public EditBookViewModel(IDialogService dialogService)
-
{
-
-
DialogService = dialogService;
-
}
-
private IDialogService dialogService;
-
-
public IDialogService DialogService
-
{
-
get { return dialogService; }
-
set { dialogService = value; }
-
}
并使用方法
DialogService.ShowMessage(EditBookArgs.IsEdit ? "编辑成功" : "新增成功");