MVVMLight安装之后,我们可以看到简易的框架布局,如上篇,生成了一个ViewModel文件夹,ViewModel层的内容都放在这边,除了Main对象的ViewModel之外,还包含一个ViewModelLocator文件,
用来注入当前的ViewModel全局实例。
一、先来说说分层结构:
如图:
1、View负责前端展示,与ViewModel进行数据和命令的交互。
2、ViewModel,负责前端视图业务级别的逻辑结构组织,并将其反馈给前端。
3、Model,主要负责数据实体的结构处理,与ViewModel进行交互。
根据上述的分层,我们来进行编码。
先建立一个完整三层结构的目录,如图,包含Model、View、ViewModel三层文件夹:
1、写一个Model,代码如下:
1 using GalaSoft.MvvmLight; 2 using System; 3 using System.Collections.Generic; 4 using System.Linq; 5 using System.Text; 6 using System.Threading.Tasks; 7 8 namespace MVVMLightDemo.Model 9 { 10 public class WelcomeModel : ObservableObject 11 { 12 private String introduction; 13 /// <summary> 14 /// 欢迎词 15 /// </summary> 16 public String Introduction 17 { 18 get { return introduction; } 19 set { introduction = value; RaisePropertyChanged(()=>Introduction); } 20 } 21 } 22 }
很简单,仅仅是包含一个实体对象,这边注意的的是那他继承了一个父类:ObservableObject,这个父类的作用就是保证能够检测属性是否被改变。
它实现了INotifyPropertyChanged接口,通过触发PropertyChanged事件达到通知UI更改的目的;
所以我们在定义实体对象的时候,只需要调用RaisePropertyChanged(PropertyName)就可以进行属性更改通知了。
所以实体里面定义的每个属性都加上RaisePropertyChanged(PropertyName)的调用,就可以实现对UI的交互更新了。
2、写一个VideModel,来负责跟View的交互。
1 using GalaSoft.MvvmLight; 2 using MVVMLightDemo.Model; 3 using System; 4 using System.Collections.Generic; 5 using System.Linq; 6 using System.Text; 7 using System.Threading.Tasks; 8 9 namespace MVVMLightDemo.ViewModel 10 { 11 public class WelcomeViewModel:ViewModelBase 12 { 13 /// <summary> 14 /// 构造函数 15 /// </summary> 16 public WelcomeViewModel() 17 { 18 Welcome = new WelcomeModel() { Introduction = "Hello World!" }; 19 } 20 #region 属性 21 22 private WelcomeModel welcome; 23 /// <summary> 24 /// 欢迎词属性 25 /// </summary> 26 public WelcomeModel Welcome 27 { 28 get { return welcome; } 29 set { welcome = value; RaisePropertyChanged(()=>Welcome); } 30 } 31 #endregion 32 } 33 }
也很简单,包含了一个命名为Welcome的WelcomeModel属性,继承了ViewBaseModel父类,
ViewBaseModel同时继承 ObservableObject类和ICleanup接口。所以他同样有INotifyPropertyChanged接口的能力,
能够通过触发PropertyChanged事件达到通知View的目的;
构造函数中对 Welcome 属性进行了实例化。
3、写一个View,来显示和交互ViewModel。
1 <Window x:Class="MVVMLightDemo.View.WelcomeView" 2 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 3 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 4 Title="WelcomeView" Height="300" Width="300"> 5 <Grid> 6 <StackPanel VerticalAlignment="Center" HorizontalAlignment="Center" > 7 <TextBlock Text="{Binding Welcome.Introduction}" FontSize="30" ></TextBlock> 8 </StackPanel> 9 </Grid> 10 </Window>
TextBlock 绑定了 Welcome.Introduction,所以应该显示Welcome对象下的Introduction属性。
这时候的ViewModel和View是没有任何关系的,所以我们在code-Behind的构造函数中写上如下代码:
1 using MVVMLightDemo.ViewModel; 2 using System.Windows; 3 4 namespace MVVMLightDemo.View 5 { 6 /// <summary> 7 /// Interaction logic for WelcomeView.xaml 8 /// </summary> 9 public partial class WelcomeView : Window 10 { 11 public WelcomeView() 12 { 13 InitializeComponent(); 14 this.DataContext = new WelcomeViewModel(); 15 } 16 } 17 }
把 WelcomeViewModel 赋值给当前视图的数据上下文。所以可以在当前视图中使用ViewModel中所有的公开属性和命令。
执行效果如下: