MVVMLight学习笔记(二)---MVVMLight框架初探
一、MVVM分层概述
MVVM中,各个部分的职责如下:
Model:负责数据实体的结构处理,与ViewModel进行交互;
public class ViewModelLocator
{
/// <summary>
/// Initializes a new instance of the ViewModelLocator class.
/// </summary>
public ViewModelLocator()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default); ////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>();
////} SimpleIoc.Default.Register<MainViewModel>();
} public MainViewModel Main
{
get
{
return ServiceLocator.Current.GetInstance<MainViewModel>();
}
} public static void Cleanup()
{
// TODO Clear the ViewModels
}
}
在构造函数中,创建了一个SimpleIoc类型的单实例,用于注册ViewModel,然后用ServiceLocator对这个SimpleIoc类型的单实例进行包裹,方便统一管理。
观察App.xaml文件,我们会发现ViewModelLocator类被生成资源字典并加入到了全局资源,所以每次App初始化的时候,就会去初始化ViewModelLocator类。
<Application x:Class="MvvmLightDemo.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:MvvmLightDemo" StartupUri="MainWindow.xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
d1p1:Ignorable="d" xmlns:d1p1="http://schemas.openxmlformats.org/markup-compatibility/2006">
<Application.Resources>
<ResourceDictionary>
<vm:ViewModelLocator x:Key="Locator" d:IsDataSource="True" xmlns:vm="clr-namespace:MvvmLightDemo.ViewModel" />
</ResourceDictionary>
</Application.Resources>
</Application>
由此分析,我们可以得出以下一般结论:
当我们自定义一个ViewModel的时候,就可以在ViewModelLocator类的构造函数中对ViewModel进行注册,然后在该类中定义一个属性,用于返回我们的自定义ViewModel
三、MVVMLight框架初探实战Demo
在建立一个MVVMLight框架的Wpf工程后,我们再在工程下建立Model和View(该文件夹在本Demo中暂时不用,我们只使用主窗口)文件夹,VIewModel文件夹框架已经自动帮我们建立了,无需再创建。
1)在Model文件夹下建立一个WelcomeModel .cs文件,文件内容如下:
using GalaSoft.MvvmLight; namespace MvvmLightDemo1.Model
{
public class WelcomeModel : ObservableObject
{
private string welcomeMsg;
public string WelcomeMsg
{
get { return welcomeMsg; }
set { welcomeMsg = value; RaisePropertyChanged(() => WelcomeMsg); }
}
} }
类WelcomeModel继承自类ObservableObject,并包含一个简单的string类型的WelcomeMsg属性,用于显示欢迎信息。
类ObservableObject位于GalaSoft.MvvmLight命名空间,实现INotifyPropertyChanged接口,通过触发PropertyChanged事件达到通知UI属性更改的目的。
所以,我们在定义实体对象的时候,只需要在属性的set块中调用RaisePropertyChanged(PropertyName)就可以进行属性更改通知,实现与UI的交互。
2)在MainViewModel中定义一个WelcomeModel类型的属性WelcomeModel,并在构造函数中对该属性进行初始化。
using GalaSoft.MvvmLight;
using MvvmLightDemo1.Model; namespace MvvmLightDemo1.ViewModel
{
/// <summary>
/// This class contains properties that the main View can data bind to.
/// <para>
/// Use the <strong>mvvminpc</strong> snippet to add bindable properties to this ViewModel.
/// </para>
/// <para>
/// You can also use Blend to data bind with the tool's support.
/// </para>
/// <para>
/// See http://www.galasoft.ch/mvvm
/// </para>
/// </summary>
public class MainViewModel : ViewModelBase
{
private WelcomeModel welcomeModel;
public WelcomeModel WelcomeModel
{
get { return welcomeModel; }
set { welcomeModel = value; RaisePropertyChanged(() => WelcomeModel); }
}
/// <summary>
/// Initializes a new instance of the MainViewModel class.
/// </summary>
public MainViewModel()
{
WelcomeModel = new WelcomeModel() { WelcomeMsg = "Welcome to MVVMLight World!" };
}
}
}
3)修改主窗口
<Window x:Class="MvvmLightDemo1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:MvvmLightDemo1"
mc:Ignorable="d"
Title="MVVMLIghtDemo1" Height="350" Width="525" Background="#FF256795">
<Window.DataContext>
<Binding Path="Main" Source="{StaticResource Locator}"></Binding>
</Window.DataContext>
<Grid>
<StackPanel VerticalAlignment="Top" HorizontalAlignment="Center" >
<TextBlock Text="{Binding WelcomeModel.WelcomeMsg}" FontSize="28" Foreground="#FF128738"></TextBlock>
</StackPanel>
</Grid>
</Window>
TextBlock 绑定了 WelcomeModel中的WelcomeMsg,用于显示欢迎信息。
然后,我们通过ViewModelLocator的Main属性返回MainViewModel,将它赋值给MainWindow的DataContext属性,完成VIew和ViewModel的关联。
<Binding Path="Main" Source="{StaticResource Locator}"></Binding>
</Window.DataContext>
<Application x:Class="MvvmLightDemo1.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:MvvmLightDemo1"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
d1p1:Ignorable="d" xmlns:d1p1="http://schemas.openxmlformats.org/markup-compatibility/2006"
StartupUri="MainWindow.xaml">
<Application.Resources>
<ResourceDictionary>
<vm:ViewModelLocator x:Key="Locator" d:IsDataSource="True" xmlns:vm="clr-namespace:MvvmLightDemo1.ViewModel" />
</ResourceDictionary>
</Application.Resources>
</Application>
ViewModelLocator.cs文件内容如下:
/*
In App.xaml:
<Application.Resources>
<vm:ViewModelLocator xmlns:vm="clr-namespace:MvvmLightDemo1"
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 CommonServiceLocator;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Ioc; namespace MvvmLightDemo1.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); ////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>();
////} SimpleIoc.Default.Register<MainViewModel>();
} public MainViewModel Main
{
get
{
return ServiceLocator.Current.GetInstance<MainViewModel>();
}
} public static void Cleanup()
{
// TODO Clear the ViewModels
}
}
}
至此,一个初级的MVVMLight项目就构建完成了。
运行结果如下:
MVVMLight学习笔记(二)---MVVMLight框架初探的更多相关文章
- [Firefly引擎][学习笔记二][已完结]卡牌游戏开发模型的设计
源地址:http://bbs.9miao.com/thread-44603-1-1.html 在此补充一下Socket的验证机制:socket登陆验证.会采用session会话超时的机制做心跳接口验证 ...
- muduo学习笔记(二)Reactor关键结构
目录 muduo学习笔记(二)Reactor关键结构 Reactor简述 什么是Reactor Reactor模型的优缺点 poll简述 poll使用样例 muduo Reactor关键结构 Chan ...
- qml学习笔记(二):可视化元素基类Item详解(上半场anchors等等)
原博主博客地址:http://blog.csdn.net/qq21497936本文章博客地址:http://blog.csdn.net/qq21497936/article/details/78516 ...
- 转)delphi chrome cef3 控件学习笔记 (二)
(转)delphi chrome cef3 控件学习笔记 (二) https://blog.csdn.net/risesoft2012/article/details/51260832 原创 2016 ...
- WPF的Binding学习笔记(二)
原文: http://www.cnblogs.com/pasoraku/archive/2012/10/25/2738428.htmlWPF的Binding学习笔记(二) 上次学了点点Binding的 ...
- AJax 学习笔记二(onreadystatechange的作用)
AJax 学习笔记二(onreadystatechange的作用) 当发送一个请求后,客户端无法确定什么时候会完成这个请求,所以需要用事件机制来捕获请求的状态XMLHttpRequest对象提供了on ...
- JMX学习笔记(二)-Notification
Notification通知,也可理解为消息,有通知,必然有发送通知的广播,JMX这里采用了一种订阅的方式,类似于观察者模式,注册一个观察者到广播里,当有通知时,广播通过调用观察者,逐一通知. 这里写 ...
- java之jvm学习笔记二(类装载器的体系结构)
java的class只在需要的时候才内转载入内存,并由java虚拟机的执行引擎来执行,而执行引擎从总的来说主要的执行方式分为四种, 第一种,一次性解释代码,也就是当字节码转载到内存后,每次需要都会重新 ...
- Java IO学习笔记二
Java IO学习笔记二 流的概念 在程序中所有的数据都是以流的方式进行传输或保存的,程序需要数据的时候要使用输入流读取数据,而当程序需要将一些数据保存起来的时候,就要使用输出流完成. 程序中的输入输 ...
- 《SQL必知必会》学习笔记二)
<SQL必知必会>学习笔记(二) 咱们接着上一篇的内容继续.这一篇主要回顾子查询,联合查询,复制表这三类内容. 上一部分基本上都是简单的Select查询,即从单个数据库表中检索数据的单条语 ...
随机推荐
- C语言:异或
异或运算符"∧"也称XOR运算符.它的规则是若参加运算的两个二进位同号,则结果为0(假):异号则为1(真).即 0∧0=0,0∧1=1, 1^0=1,1∧1=0. 相同为0,不相同 ...
- python 获取当前py文件所在的位置 及对应的文件名称
# 导入sys整个模块 import sys # 使用sys模块名作为前缀来访问模块中的成员 print(sys.argv[0]) 当前文件名:12.py 程序运行结果: ============== ...
- 团队开发day07
开始整合项目,测试登录,注册,搜索功能, 在安卓中数据处理存在个别错误,功能逻辑有个别不正确 进行修改和完善,添加二次确认退出
- java课堂动手动脑及课后实验总结
动手动脑一:枚举 输出结果: false false true SMALL MEDIUM LARGE 分析和总结用法 枚举类型的使用是借助ENUM这样一个类,这个类是JAVA枚举类型的公共基本 ...
- Python爬虫下载酷狗音乐
目录 1.Python下载酷狗音乐 1.1.前期准备 1.2.分析 1.2.1.第一步 1.2.2.第二步 1.2.3.第三步 1.2.4.第四步 1.3.代码实现 1.4.运行结果 1.Python ...
- python基础之操作数据库(pymysql)操作
import pymysqlimport datetime#安装 pip install pymysql"""1.连接本地数据库2.建立游标3.创建表4.插入表数据.查询 ...
- Go LRU Cache 抛砖引玉
目录 1. LRU Cache 2. container/list.go 2.1 list 数据结构 2.2 list 使用例子 3. transport.go connLRU 4. 结尾 正文 1. ...
- 动态 DP
一道入门 DP + 修改 = 动态 DP. 以模板题为例,多次询问树的最大独立集,带修改. 先有 naive 的 DP,记 \(f_{u,0/1}\) 表示 \(u\) 点不选/选时以 \(u\) 为 ...
- 单点登录详解(token简述)(七)
前言 为什么整理单点登录? 主要的原因还是自己以前学习的时候曾经用过,但是时间太久,忘记了里面用到了哪些技术.及如何实现的,每次想到单点登录总是感觉即会又不会,这次整理session时,又涉及到了单点 ...
- c语言学习篇二【基础语法】
一.定义常量: 使用 #define 预处理器. 使用 const 关键字. #include <stdio.h> int main() { const int LENGTH = 10;/ ...