写了篇MVVM小记http://www.cnblogs.com/whosedream/p/mvvmnote1.html,说好要写点MVVMLight的东西,所以接着写,以便和大家共勉。

  我假设你已经有了MVVM的一些概念,那么我们就单刀直入了,怎样基于MVVMLight 来建项目呢?其实很简单,首先我们需要下载MVVMLight,然后安装,完了你会看到

Binaries里有各个版本的程序集

这里我用到了silverlight4的程序集

不过你安装了模板的话,新建模板项目,那么上面这些程序集就不用你手动去添加了,我用的是VS2012,所以安装了下面的第二个模板MvvmLight.VS2012.vsix

现在可以新建项目了,在新建项目silverlight选项里你会多看见2个选项

我用的是SL4那么我就选择第一个新建

我们可以看到一个大体的架子帮你搭出来了,按F5运行,会看到

恭喜你的第一个MVVMLight应用完成了!!!让我们看看都写了些什么。

找到程序的入口App

<Application xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="MvvmLightTest.App"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:vm="clr-namespace:MvvmLightTest.ViewModel"
mc:Ignorable="d">
<Application.Resources>
<!--Global View Model Locator-->
<vm:ViewModelLocator x:Key="Locator"
d:IsDataSource="True" />
</Application.Resources>
</Application>

我们看到添加了个应用程序资源ViewModelLocator,这是干什么用的呢,下面再说,看看App.cs里写了些什么

  private void Application_Startup(object sender, StartupEventArgs e)
{
RootVisual = new MainPage();
DispatcherHelper.Initialize();
} private void Application_Exit(object sender, EventArgs e)
{
ViewModelLocator.Cleanup();
}

和以前的代码相比,在程序退出里我们又看到了ViewModelLocator,看来这东西是贯穿我们应用程序始终的,待会再说。我们还发现在启动里多了个 DispatcherHelper.Initialize(),这是初始化什么的呢?

...
public static void Initialize()
{
if (UIDispatcher == null)
{
UIDispatcher = Deployment.Current.Dispatcher;
}
} public static Dispatcher UIDispatcher
{
get;
private set;
}
...

看到了吗?它会获取当前应用程序的Dispatcher,Dispatcher是干什么用的?跨线程操作的时候你就会用到。

好了我们的程序RootVisual已经置了MainPage了,看看MainPage有什么

<UserControl x:Class="MvvmLightTest.MainPage"
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:ignore="http://www.ignore.com"
mc:Ignorable="d ignore"
Height="300"
Width="300"
DataContext="{Binding Main, Source={StaticResource Locator}}"> <UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Skins/MainSkin.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</UserControl.Resources> <Grid x:Name="LayoutRoot"> <TextBlock FontSize="36"
FontWeight="Bold"
Foreground="Purple"
Text="{Binding WelcomeTitle}"
VerticalAlignment="Center"
HorizontalAlignment="Center"
TextWrapping="Wrap" /> </Grid>
</UserControl>

是不是还奇怪App里怎么MainPage没有对DataContext进行赋值,原来在这里

DataContext="{Binding  Main, Source={StaticResource Locator}}"

这里Locator是不是很熟悉,啊~对了,就是App的资源文件里添加的东西。现在我们来看看到底ViewModelLocator扮演着何方神圣。

 public class ViewModelLocator
{
static ViewModelLocator()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default); if (ViewModelBase.IsInDesignModeStatic)
{
SimpleIoc.Default.Register<IDataService, Design.DesignDataService>();
}
else
{
SimpleIoc.Default.Register<IDataService, DataService>();
} SimpleIoc.Default.Register<MainViewModel>();
} /// <summary>
/// Gets the Main property.
/// </summary>
public MainViewModel Main
{
get
{
return ServiceLocator.Current.GetInstance<MainViewModel>();
}
} /// <summary>
/// Cleans up all the resources.
/// </summary>
public static void Cleanup()
{
}
}
ServiceLocator SimpleIoc 这两个东西比较陌生,看ServiceLocator的注释

This class provides the ambient container for this application. If your framework
defines such an ambient container, use ServiceLocator.Current to get it.

  该类为应用程序提供了一个容器,如果你的框架定义了这么一个容器,那么你可以用ServiceLocator.Current来获取。

  既然是个容器,那么是干嘛的呢?继续看代码,ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);为这个容器置一个委托SimpleIoc.Default,可能看到IOC,马上就想到了控制反转,依赖注入。对~SimpleIoc就是MVVMLight实现的一个IOC容器,再看SimpleIoc.Default.Register方法,你就明白原来是往容器里塞东西(接口实现,类)。

有放就有取

public MainViewModel Main
{
get
{
return ServiceLocator.Current.GetInstance<MainViewModel>();
}
}

这也是页面绑定的属性

到现在我们只看到了个ViewModel的属性,嗯,看看ViewModel是怎样的

  public class MainViewModel : ViewModelBase
{
private readonly IDataService _dataService; /// <summary>
/// The <see cref="WelcomeTitle" /> property's name.
/// </summary>
public const string WelcomeTitlePropertyName = "WelcomeTitle"; private string _welcomeTitle = string.Empty; /// <summary>
/// Gets the WelcomeTitle property.
/// Changes to that property's value raise the PropertyChanged event.
/// </summary>
public string WelcomeTitle
{
get
{
return _welcomeTitle;
} set
{
if (_welcomeTitle == value)
{
return;
} _welcomeTitle = value;
RaisePropertyChanged(WelcomeTitlePropertyName);
}
} /// <summary>
/// Initializes a new instance of the MainViewModel class.
/// </summary>
public MainViewModel(IDataService dataService)
{
_dataService = dataService;
_dataService.GetData(
(item, error) =>
{
if (error != null)
{
// Report error here
return;
} WelcomeTitle = item.Title;
});
} ////public override void Cleanup()
////{
//// // Clean up if needed //// base.Cleanup();
////}
}

  它继承了ViewModelBase,其实它还是实现了 INotifyPropertyChanged, System.ComponentModel.INotifyPropertyChanging这些个东西

是不是没有发现Model,呵呵,WelcomeTitle 不就是Model吗?

  今天到此为止,源码下载 如果对您有所帮助的话就顶个吧。

【MVVMLight小记】一.快速搭建一个基于MVVMLight的silverlight小程序的更多相关文章

  1. 快速搭建一个基于react的项目

    最近在学习react,快速搭建一个基于react的项目 1.创建一个放项目文件夹,用编辑器打开 2.打开集成终端输入命令: npm install -g create-react-app 3. cre ...

  2. 用Python快速实现一个垃圾分类APP|附带微信小程序

    最近北京开始实行垃圾分类,导致大家对垃圾的研究热度突然涨高,垃圾们也纷纷表示从来没有获得过这么高的关注度.其实,上海市去年已经开始实行,网上已经有不少成熟的教程了,像什么<垃圾分类从入门到精通& ...

  3. 如何快速搭建一个基于ServiceStack框架的web服务

    ServiceStack是一个高性能的.NET Web Service 平台,能够简化开发高性能的REST (支持JSON,XML,JSV,HTML,MsgPack,ProtoBuf,CSV等消息格式 ...

  4. 【MVVMLight小记】二.开发一个简单图表生成程序附源码

    上一篇文章介绍了怎样快速搭建一个基于MVVMLight的程序http://www.cnblogs.com/whosedream/p/mvvmlight1.html算是简单入门了下,今天我们来做一个稍许 ...

  5. [原创] zabbix学习之旅五:如何快速搭建一个报警系统

    通过之前的文章,我们已搭建好zabbix server.agent和mail客户端,现在万事俱备,只差在server的界面中进行相应配置,即可快速搭建一个报警系统.总的来说,快速搭建一个报警系统的顺序 ...

  6. 【Head First Servlets and JSP】笔记6:什么是响应首部 & 快速搭建一个简单的测试环境

    搭建简单的测试环境 什么是响应首部 最简单的响应首部——Content-Type 设置响应首部 请求重定向与响应首部 在浏览器中查看Response Headers 1.先快速搭建一个简单的测试环境, ...

  7. jquery+flask+keras+nsfw快速搭建一个简易鉴黄工具

    1. demo 地址:http://www.huchengchun.com:8127/porn_classification 接口说明: 1. http://www.huchengchun.com:8 ...

  8. NodeJS 最快速搭建一个HttpServer

    最快速搭建一个HttpServer 在目录里放一个index.html cd D:\Web\InternalWeb start http-server -i -p 8081

  9. vuejsLearn---通过手脚架快速搭建一个vuejs项目

    开始快速搭建一个项目 通过Webpack + vue-loader 手脚架 https://github.com/vuejs-templates/webpack 按照它的步骤一步一步来 $ npm i ...

随机推荐

  1. iOS实现自定义进度条、拖动条效果,可多个

    项目用到的一个场景,需要设置一个周期内不同时间时的数值 比如要设置10秒内,每一秒的大小,通过10个拖动条来设置实现,只需拖动到想要的数值即可, 这里周期10秒和每个拖动条的最大值都是可以自己定义的. ...

  2. 未进入Kali Linux系统修改修改密码的方法

    今天使用kali的时候,由于虚拟机太多,密码还不一样,就忘记kali的登录密码了(我就是鱼的记忆,只有七秒).... 1.重启kali,进入恢复系统,按e键进入编辑模式 2.光标移动到/boot/vm ...

  3. linux tomcat 用/etc/init.d/tomcat start启动报错

    line 13: [ 0: unary operator expected please use "sudo service tomcat stop|start|restart" ...

  4. hadoop2.6.2分布式环境搭建

    1.准备三台机器,机器名是:master.slave01.slave02 1.1 最小化安装centos6.5 1.2 安装ssh,yum -y install openssh-clients(这一步 ...

  5. PHP正确的使用复数

    <?php // 正确地显示复数 if(!function_exists('_plurals_format')) { /** * 正确的使用复数 * @access public * @auth ...

  6. Spring之IoC总结帖

    Spring是一个开源框架,Spring是于2003 年兴起的一个轻量级的Java 开发框架,由Rod Johnson 在其著作Expert One-On-One J2EE Development a ...

  7. WinCE项目应用之RM905a+医用放射性核素活度计

    RM905a+医用放射性核素活度计大概是我做的第一个WinCE项目,RM905a的升级版.RM905a是曾经的老大LZF 2000年左右的作品,基于51单片机开发,数码管显示,稳定可靠,好似目前还在生 ...

  8. instanceof

    java 中的instanceof 运算符是用来在运行时指出对象是否是特定类的一个实例. instanceof通过返回一个布尔值来指出,这个对象是否是这个特定类或者是它的子类的一个实例. result ...

  9. 如何用patch打补丁

    patch -p1 < *.patch -p1代表忽略第一层目录(patch文件中的).

  10. javascript获取元素的方法[xyyit]

    1. javascript默认的方法: <div id=”div_id” class=”div_class” name=”div_name”></div> //1. 根据id ...