網(wǎng)站首頁(yè) 編程語(yǔ)言 正文
MVVMLight項(xiàng)目Model?View結(jié)構(gòu)及全局視圖模型注入器_Android
作者:Brand ? 更新時(shí)間: 2022-04-11 編程語(yǔ)言MVVM和MVVMLight框架介紹及在項(xiàng)目中的使用詳解
上一篇我們已經(jīng)介紹了如何使用NuGet把MVVMLight應(yīng)用到我們的WPF項(xiàng)目中。這篇我們來(lái)了解下一個(gè)基本的MVVMLight框架所必須的結(jié)構(gòu)和運(yùn)行模式。
MVVMLight安裝之后,我們可以看到簡(jiǎn)易的框架布局,如上篇,生成了一個(gè)ViewModel文件夾,ViewModel層的內(nèi)容都放在這邊,除了Main對(duì)象的ViewModel之外,還包含一個(gè)ViewModelLocator文件,
用來(lái)注入當(dāng)前的ViewModel全局實(shí)例。
一、先來(lái)說(shuō)說(shuō)分層結(jié)構(gòu):
如圖:
1、View負(fù)責(zé)前端展示,與ViewModel進(jìn)行數(shù)據(jù)和命令的交互。
2、ViewModel,負(fù)責(zé)前端視圖業(yè)務(wù)級(jí)別的邏輯結(jié)構(gòu)組織,并將其反饋給前端。
3、Model,主要負(fù)責(zé)數(shù)據(jù)實(shí)體的結(jié)構(gòu)處理,與ViewModel進(jìn)行交互。
根據(jù)上述的分層,我們來(lái)進(jìn)行編碼。
先建立一個(gè)完整三層結(jié)構(gòu)的目錄,如圖,包含Model、View、ViewModel三層文件夾:
1、寫一個(gè)Model,代碼如下:
using GalaSoft.MvvmLight; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MVVMLightDemo.Model { public class WelcomeModel : ObservableObject { private String introduction; /// <summary> /// 歡迎詞 /// </summary> public String Introduction { get { return introduction; } set { introduction = value; RaisePropertyChanged(()=>Introduction); } } }
很簡(jiǎn)單,僅僅是包含一個(gè)實(shí)體對(duì)象,這邊注意的的是那他繼承了一個(gè)父類:ObservableObject,這個(gè)父類的作用就是保證能夠檢測(cè)屬性是否被改變。
它實(shí)現(xiàn)了INotifyPropertyChanged接口,通過觸發(fā)PropertyChanged事件達(dá)到通知UI更改的目的;
所以我們?cè)诙x實(shí)體對(duì)象的時(shí)候,只需要調(diào)用RaisePropertyChanged(PropertyName)就可以進(jìn)行屬性更改通知了。
所以實(shí)體里面定義的每個(gè)屬性都加上RaisePropertyChanged(PropertyName)的調(diào)用,就可以實(shí)現(xiàn)對(duì)UI的交互更新了。
2、寫一個(gè)VideModel,來(lái)負(fù)責(zé)跟View的交互。
using GalaSoft.MvvmLight; using MVVMLightDemo.Model; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MVVMLightDemo.ViewModel { public class WelcomeViewModel:ViewModelBase { /// <summary> /// 構(gòu)造函數(shù) /// </summary> public WelcomeViewModel() { Welcome = new WelcomeModel() { Introduction = "Hello World!" }; } #region 屬性 private WelcomeModel welcome; /// <summary> /// 歡迎詞屬性 /// </summary> public WelcomeModel Welcome { get { return welcome; } set { welcome = value; RaisePropertyChanged(()=>Welcome); } } #endregion } }
也很簡(jiǎn)單,包含了一個(gè)命名為Welcome的WelcomeModel屬性,繼承了ViewBaseModel父類,
ViewBaseModel同時(shí)繼承 ObservableObject類和ICleanup接口。所以他同樣有INotifyPropertyChanged接口的能力,
能夠通過觸發(fā)PropertyChanged事件達(dá)到通知View的目的;
構(gòu)造函數(shù)中對(duì) Welcome 屬性進(jìn)行了實(shí)例化。
3、寫一個(gè)View,來(lái)顯示和交互ViewModel。
<Window x:Class="MVVMLightDemo.View.WelcomeView" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="WelcomeView" Height="300" Width="300"> <Grid> <StackPanel VerticalAlignment="Center" HorizontalAlignment="Center" > <TextBlock Text="{Binding Welcome.Introduction}" FontSize="30" ></TextBlock> </StackPanel> </Grid> </Window>
?TextBlock 綁定了 Welcome.Introduction,所以應(yīng)該顯示W(wǎng)elcome對(duì)象下的Introduction屬性。
這時(shí)候的ViewModel和View是沒有任何關(guān)系的,所以我們?cè)赾ode-Behind的構(gòu)造函數(shù)中寫上如下代碼:?
using MVVMLightDemo.ViewModel; using System.Windows; namespace MVVMLightDemo.View { /// <summary> /// Interaction logic for WelcomeView.xaml /// </summary> public partial class WelcomeView : Window { public WelcomeView() { InitializeComponent(); this.DataContext = new WelcomeViewModel(); } }
把 WelcomeViewModel 賦值給當(dāng)前視圖的數(shù)據(jù)上下文。所以可以在當(dāng)前視圖中使用ViewModel中所有的公開屬性和命令。
執(zhí)行效果如下:
二、再來(lái)說(shuō)說(shuō)構(gòu)造器:
如果使用NuGet安裝的是完整的一個(gè)是MVVM Light 框架,而非 MVVM Light libraries only的時(shí)候,總是會(huì)帶上ViewModelLocator類,并且生成資源字典并加入到了全局資源中。
<Application x:Class="MVVMLightDemo.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" StartupUri="View/WelcomeView.xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" d1p1:Ignorable="d" xmlns:d1p1="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:vm="clr-namespace:MVVMLightDemo.ViewModel" > <Application.Resources> <ResourceDictionary> <vm:ViewModelLocator x:Key="Locator" d:IsDataSource="True" /> </ResourceDictionary> </Application.Resources> </Application>
所以每次App初始化的時(shí)候,就會(huì)去初始化ViewModelLocator類。
實(shí)際上他就是一個(gè)很基本的視圖模型注入器。在構(gòu)造器中把使用到的ViewModel統(tǒng)一注冊(cè),并生成單一實(shí)例。
然后使用屬性把它暴露出來(lái),每當(dāng)我們?cè)L問屬性的時(shí)候,就會(huì)返回相應(yīng)的ViewModel實(shí)例。
/* In App.xaml: <Application.Resources> <vm:ViewModelLocator xmlns:vm="clr-namespace:MVVMLightDemo" x:Key="Locator" /> </Application.Resources> In the View: DataContext="{Binding Source={StaticResource Locator}, Path=ViewModelName}" You can also use Blend to do all this with the tool's support. See http://www.galasoft.ch/mvvm */ using GalaSoft.MvvmLight; using GalaSoft.MvvmLight.Ioc; using Microsoft.Practices.ServiceLocation; namespace MVVMLightDemo.ViewModel { /// <summary> /// This class contains static references to all the view models in the /// application and provides an entry point for the bindings. /// </summary> public class ViewModelLocator { /// <summary> /// Initializes a new instance of the ViewModelLocator class. /// </summary> public ViewModelLocator() { ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default); #region Code Example ////if (ViewModelBase.IsInDesignModeStatic) ////{ //// // Create design time view services and models //// SimpleIoc.Default.Register<IDataService, DesignDataService>(); ////} ////else ////{ //// // Create run time view services and models //// SimpleIoc.Default.Register<IDataService, DataService>(); ////} #endregion SimpleIoc.Default.Register<MainViewModel>(); } #region 實(shí)例化 public MainViewModel Main { get { return ServiceLocator.Current.GetInstance<MainViewModel>(); } } #endregion public static void Cleanup() { // TODO Clear the ViewModels } }
注意的是,這邊把MVVMLight 自帶的SimpleIoc作為默認(rèn)的服務(wù)提供者,它是個(gè)簡(jiǎn)易的注入框架。
為了統(tǒng)一化,并且在設(shè)計(jì)的時(shí)候可以看到看到ViewModel的數(shù)據(jù),這邊用ServiceLocator 又將SimpleIoc包裹了一層。
上面我們寫了一個(gè)Hello World,這時(shí)候就可以用這種方式改裝了。
/* In App.xaml: <Application.Resources> <vm:ViewModelLocator xmlns:vm="clr-namespace:MVVMLightDemo" x:Key="Locator" /> </Application.Resources> In the View: DataContext="{Binding Source={StaticResource Locator}, Path=ViewModelName}" You can also use Blend to do all this with the tool's support. See http://www.galasoft.ch/mvvm */ using GalaSoft.MvvmLight; using GalaSoft.MvvmLight.Ioc; using Microsoft.Practices.ServiceLocation; namespace MVVMLightDemo.ViewModel { /// <summary> /// This class contains static references to all the view models in the /// application and provides an entry point for the bindings. /// </summary> public class ViewModelLocator { /// <summary> /// Initializes a new instance of the ViewModelLocator class. /// </summary> public ViewModelLocator() { ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default); #region Code Example ////if (ViewModelBase.IsInDesignModeStatic) ////{ //// // Create design time view services and models //// SimpleIoc.Default.Register<IDataService, DesignDataService>(); ////} ////else ////{ //// // Create run time view services and models //// SimpleIoc.Default.Register<IDataService, DataService>(); ////} #endregion SimpleIoc.Default.Register<MainViewModel>(); SimpleIoc.Default.Register<WelcomeViewModel>(); } #region 實(shí)例化 public MainViewModel Main { get { return ServiceLocator.Current.GetInstance<MainViewModel>(); } } public WelcomeViewModel Welcome { get { return ServiceLocator.Current.GetInstance<WelcomeViewModel>(); } } #endregion public static void Cleanup() { // TODO Clear the ViewModels } }
注冊(cè)完WelcomeViewModel實(shí)例之后,我們就可以在相應(yīng)的View中使用了 ,原本的
public WelcomeView() { InitializeComponent(); this.DataContext = new WelcomeViewModel(); }
中的 this.DataContext = new WelcomeViewModel();
可以去掉了,直接在WelcomeView中這樣寫:
DataContext="{Binding Source={StaticResource Locator},Path=Welcome}"
如下圖:
這樣做的好處,一個(gè)是綁定化相對(duì)于簡(jiǎn)單粗暴的賦值方式,更合理。一個(gè)是在可視化窗口可以看到所綁定的數(shù)據(jù),達(dá)到所見即所得的友好效果。
如下:
當(dāng)我們改掉綁定到的數(shù)據(jù),編譯之后就會(huì)立馬呈現(xiàn):
服務(wù)端開發(fā)人員可以專心寫ViewModel的業(yè)務(wù)邏輯代碼,UI開發(fā)人員可以專注設(shè)計(jì)視圖了,
同樣 ViewModel可以綁定到不同的視圖上,所以從這邊就可以體現(xiàn)出他其中的三個(gè)重要特性:低耦合、可重用性、獨(dú)立開發(fā)。
大家有沒有發(fā)現(xiàn)ViewModelLocator 類中還有個(gè) ClearnUp()方法,主要目的用來(lái)清除ViewModel實(shí)例的。
ViewModelBase繼承了GalaSoft.MvvmLight.ICleanup接口,并在自己的類中寫好了Cleanup()虛方法。所以我們?cè)趯?shí)例ViewModel類中可以重寫Cleanup()來(lái)達(dá)到清除當(dāng)前實(shí)例的目的。
原文鏈接:https://www.cnblogs.com/wzh2010/p/6285990.html
相關(guān)推薦
- 2024-04-07 Linux如何查看當(dāng)前占用CPU和內(nèi)存最多的進(jìn)程
- 2021-12-06 Flutter多項(xiàng)選擇彈窗實(shí)現(xiàn)詳解_Android
- 2023-06-18 C#?Marshal類基本概念和入門實(shí)例講解_C#教程
- 2022-12-04 Python學(xué)習(xí)之字典和集合的使用詳解_python
- 2023-11-21 linux sudo:/etc/sudoers 中第 11 行附近有解析錯(cuò)誤 sudo:no val
- 2022-04-27 python?數(shù)據(jù)挖掘算法的過程詳解_python
- 2022-07-01 Python查詢?nèi)笔е档?種方法總結(jié)_python
- 2022-03-24 聊一聊redis奇葩數(shù)據(jù)類型與集群知識(shí)_Redis
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲(chǔ)小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯(cuò)誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡(jiǎn)單動(dòng)態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對(duì)象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支