一 界面控件DevExpress WinForm - MVVM服务讲解

DevExpress Universal Subscription官方最新版免费下载试用,历史版本下载,在线文档和帮助文件下载-慧都网
考虑像显示来自 ViewModel 的通知(例如,消息框)这样的微不足道的任务,作为可视化元素,任何消息框实际上都是视图的一部分 。因此,如果你直接从 ViewModel 显示消息框(定义一个调用 MessageBox.Show 方法的命令),这个简单的代码将破坏主要的MVVM概念 - ViewModels不能引用Views,并使其无法编写ViewModel的单元测试 。为了解决这个困难,DevExpress MVVM 框架实现了服务 。
服务是一种 IOC 模式,它删除了 ViewModel 和 View 层之间的任何引用 。在代码中,服务是在 ViewModel 代码中使用的接口,没有任何关于“何时”和“如何”实现该接口的假设 。
【一 界面控件DevExpress WinForm - MVVM服务讲解】您可以实现自己的自定义服务以及使用 DevExpress Services,无论您使用什么服务,通用工作流程都保持不变:
在代码中定义服务(如果您使用的是 DevExpress 已经实现的服务,则跳过);在特定的视图中注册它;在ViewModel中检索服务并使用其方法 。DevExpress ServicesDevExpress MVVM框架已经为大多数常见任务提供了现成的服务——显示消息、弹出窗口、对话框、添加应用程序 UI 管理器文档等 。例如,以下 ViewModel 代码通过定义 IMessageBoxService 类型的属性来检索 XtraMessageBoxService 。
C#
//ViewModelpublic class MyViewModel {protected IMessageBoxService MessageBoxService {get { return this.GetServiceIMessageBoxService; }}}VB.NET
'ViewModelPublic Class MyViewModelProtected ReadOnly Property MessageBoxService As IMessageBoxServiceGetReturn Me.GetService(Of IMessageBoxService)End GetEnd Property重要提示:GetService方法不是线程安全的,不应从后台线程调用 。
对于 POCO ViewModel,您可以使用以下故障安全语法,该语法将自动使用 this.GetService 方法或在出现问题时引发异常 。
C#
//POCO ViewModelprotected virtual IMessageBoxService MessageBoxService {get { throw new System.NotImplementedException; }}VB.NET
//POCO ViewModelProtected Overridable ReadOnly Property MessageBoxService As IMessageBoxServiceGetThrow New System.NotImplementedExceptionEnd GetEnd Property检索服务后,您可以在 ViewModel 中使用其方法:
C#
public void SayHello {MessageBoxService.Show("Hello!");}VB.NET
Public Sub SayHelloMessageBoxService.Show("Hello!")End Sub最后,在视图中注册您的服务 。服务要么注册在本地容器中以在单个 View 中使用(本地服务),要么注册到允许您在整个应用程序中使用注册服务的全局静态(单例)服务容器(全局服务) 。
C#
//Global serviceDevExpress.Mvvm.ServiceContainer.Default.RegisterService(new SomeService);//Local serviceserviceContainer.RegisterService(new SomeFilterService(ModuleType.MyCustomFilter));VB.NET
'Global serviceDevExpress.Mvvm.ServiceContainer.Default.RegisterService(New SomeService)'Local serviceserviceContainer.RegisterService(New SomeFilterService(ModuleType.MyCustomFilter))当创建 ViewModel 时,服务也可以在运行时在服务容器中注册 。
C#
this.ServiceContainer.RegisterService(new Services.AnotherService);VB.NET
Me.ServiceContainer.RegisterService(New Services.AnotherService)最后,您可以通过在此级别提供自定义服务实现来覆盖 ViewModel 层次结构中任何级别的父级服务实现 。
C#
serviceContainer.RegisterService(new NotImplementedCustomService(ModuleType.MyMainView));VB.NET
serviceContainer.RegisterService(New NotImplementedCustomService(ModuleType.MyMainView))使用 MvvmContext 组件,您无需记住这个底层服务容器机制 。该组件的 API 提供了易于使用的方法来注册全局和本地级别的服务 。


以上关于本文的内容,仅作参考!温馨提示:如遇专业性较强的问题(如:疾病、健康、理财等),还请咨询专业人士给予相关指导!

「辽宁龙网」www.liaoninglong.com小编还为您精选了以下内容,希望对您有所帮助: