Mvvm Light Toolkit for WPF/Silverlight系列之搭建mvvmlight开发框架

 
本章节,我将通过示例介绍如何搭建mvvmlight开发环境。示例中的我会针对wpf代码进行介绍,SL下有区别的地方我会注明,下载示例中会同时包含WPF和SL源代码,但是只会提供VS2010版本的示例程序。 前提条件:按照前一章节安装的模板和代码片段,或者下载 MVVM Light Toolkit V3 开发环境:VS2010/Blend4 为了方便大家了解框架
  

  本章节,我将通过示例介绍如何搭建mvvmlight开发环境。示例中的我会针对wpf代码进行介绍,SL下有区别的地方我会注明,下载示例中会同时包含WPF和SL源代码,但是只会提供VS2010版本的示例程序。

  前提条件:按照前一章节安装的模板和代码片段,或者下载 MVVM Light Toolkit V3

  开发环境:VS2010/Blend4

  为了方便大家了解框架结构,我将不使用mvvm项目模板,而是从空白项目开始创建mvvm light项目,下面将以两种使用mvmmlight框架的方式进行说明(以下示例针对WPF,SL操作步骤跟WPF基本一样,不做过多说明,大家可以在文章最后下载代码对照阅读):

  1、在VS2010中,文件\新建\WPF/SilverLight应用程序项目,项目名称MvvmlightDataBinding.SL4/MvvmlightDataBinding.WPF4

  2、添加mvvmlight引用,如果使用模板创建,会自动生成引用,而这里我们需要自己添加,这里我将MVVM Light Toolkit V3的源代码附到了示例中,因此,直接添加项目引用就可以了,如果要支持Blend的功能,还需要添加System.Windows.Interactivity.dll引用,如果安装了Blend,在.net引用列表中能找到,没有安装Blend,在示例中解决方案目录\Assemblies\GalaSoft.MvvmLight\External中能找到,添加后引用列表如下:

  

  3、在解决方案浏览器中,右键项目名称,添加新文件夹,文件夹名称为ViewModel

  4、在解决方案浏览器中,右键项目名称,添加新文件夹,文件夹名称为View

  5、为MainWindow添加ViewModel,在解决方案浏览器中,右键ViewModel文件夹,添加新类,类名称为MainViewModel,如果安装了mvvmlight模板,选择类模板为MvvmViewModel

  

  自动创建的代码如下:

using GalaSoft.MvvmLight;

namespace MvvmlightDataBinding.WPF4.ViewModel
{
    public class MainViewModel : ViewModelBase
    {
        /// <summary>
        /// Initializes a new instance of the MainViewModel class.
        /// </summary>
        public MainViewModel()
        {
            ////if (IsInDesignMode)
            ////{
            ////    // Code runs in Blend --> create design time data.
            ////}
            ////else
            ////{
            ////    // Code runs "for real": Connect to service, etc...
            ////}
        }

public override void Cleanup()
        {
            // Clean own resources if needed

base.Cleanup();
        }
    }
}

  代码很简单,我去掉了类注释,它是一个框架,继承自ViewModelBase,如果没装类模板,可以直接复制以上代码。

  6、添加类ViewModelLocator,我们叫它ViewModel加载器,在解决方案浏览器中,右键项目名称,添加新类,类名称为ViewModelLocator,如果安装了mvvmlight模板,选择类模板为MvvmViewModelLocator,自动创建的代码如下:

namespace MvvmlightDataBinding.WPF4.ViewModel

    public class ViewModelLocator
    {
        /// <summary>
        /// Initializes a new instance of the ViewModelLocator class.
        /// </summary>
        public ViewModelLocator()
        {
            ////if (ViewModelBase.IsInDesignModeStatic)
            ////{
            ////    // Create design time view models
            ////}
            ////else
            ////{
            ////    // Create run time view models
            ////}
        }

/// <summary>
        /// Cleans up all the resources.
        /// </summary>
        public static void Cleanup()
        {
            // Call ClearViewModelName() for each ViewModel.
        }
    }
}

  在Cleanup方法下面添加MainViewModel加载方法,这里要用到我们安装的代码片段,在类的空白处输入mvvm,在弹出的代码提示中选择mvvmlocatorproperty,如下:

  

  然后按2次tab键,会自动MainViewModel加载方法,代码片段要设置的地方有3个,他们以黄色背景高亮显示,其他相关联地方会自动保持与这3个地方一致,生成的方法如下:

#region MainViewModel
        private static MainViewModel _main;

/// <summary>
        /// Gets the Main property.
        /// </summary>
        public static MainViewModel MainStatic
        {
            get
            {
                if (_main == null)
                {
                    CreateMain();
                }

return _main;
            }
        }

/// <summary>
        /// Gets the Main property.
        /// </summary>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance",
            "CA1822:MarkMembersAsStatic",
            Justification = "This non-static member is needed for data binding purposes.")]
        public MainViewModel Main
        {
            get
            {
                return MainStatic;
            }
        }

/// <summary>
        /// Provides a deterministic way to delete the Main property.
        /// </summary>
        public static void ClearMain()
        {
            _main.Cleanup();
            _main = null;
        }

/// <summary>
        /// Provides a deterministic way to create the Main property.
        /// </summary>
        public static void CreateMain()
        {
            if (_main == null)
            {
                _main = new MainViewModel();
            }
        }

#endregion

  7、打开App.Xaml,先添加ViewModel命名控件引用,然后为ViewModelLocator添加一个全局的资源,app.xaml的内容如下:

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

  8、打开MainWindow.xaml文件,首先为MainWindow设置DataContext为MainViewModel,当然也可以为Grid设置DataContext,只要我们使用的时候,他在视觉树中可见的范围内,MainWindow.xaml代码如下:

<Window x:Class="MvvmlightDataBinding.WPF4.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="250" Width="300"
        DataContext="{Binding Main,Source={StaticResource Locator}}">
  <Grid>
    <TextBlock FontSize="16" Text="{Binding WelcomText}"/>
  </Grid>
</Window>

  我在窗体中放了一个TextBlock,TextBlock的Text属性绑定到WelcomText,这个WelcomText应该是DataContext对象的WelcomText属性,这里TextBlock从视觉树最顶层也就是Window继承DataContext绑定,因此这里绑定的WelcomText也就是MainViewModel的WelcomText属性,因此我们需要在MainViewModel中添加WelcomText属性,修改MainViewModel代码如下:

        public string WelcomText
        {
            get;
            set;
        }
        /// <summary>
        /// Initializes a new instance of the MainViewModel class.
        /// </summary>
        public MainViewModel()
        {
            if (IsInDesignMode)
            {
                // Code runs in Blend --> create design time data.
                WelcomText = "设计时的值";
            }
            else
            {
                // Code runs "for real": Connect to service, etc...
                WelcomText = "运行时的值";
            }
        }

  注意这里IsInDesignMode是判断当前环境是否是设计模式,这在界面和逻辑分离时非常实用,比如当业务逻辑开发未完成时,界面设计人员也可以进行设计,这时只需在IsInDesignMode为True时创造一些测试数据就可以了,同时也实现了所见即所得的界面设计模式;示例中我们在设计时和运行时窗体显示不同的值:

  设计时截图如下:

  

  运行时截图如下:

  

  OK,到这里我们已经完成搭建Mvvmlight框架了,接着我们继续看不使用ViewModelLocator来搭建Mvvm环境:

  1~5步与前面搭建标准MvvmLight框架一样。

  6、这里我们不创建ViewModelLocator,直接打开app.xaml.cs,添加如下代码:

protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

MainWindow = new MainWindow();
            MainWindow.Show();
            MainWindow.DataContext = new ViewModel.MainViewModel();
        }

  在App.xaml中去掉StarupUri属性设置。

  7、修改MainWindow.xaml,完整代码如下:

<Window x:Class="NormalMVVM.WPF4.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525"
        xmlns:vm="clr-namespace:NormalMVVM.WPF4.ViewModel"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        d:DataContext="{d:DesignInstance Type=vm:MainViewModel, IsDesignTimeCreatable=True}">
  <Grid>
    <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="36" Text="{Binding WelcomText}"/>
  </Grid>
</Window>

  注意这里没有使用全局的ViewModelLocator,要在设计时显示ViewModel的内容,需要使用d:DataContext创建一个设计时的实例,这个实例只有在设计时有效,在运行时MainWindow仍然使用app.xaml.cs中动态创建的ViewModel

  OK,运行示例,得到与前面示例相同的结果。

  综合看这两种方法,第一个是将ViewModel定义为静态的全局变量,第二个是动态创建,这里不谈孰优孰劣,我觉得应该灵活运用,一个项目往往包含很多个View和ViewModel,全部都定义为静态并不合适,因此我一般都是两种方法混合使用

  至此,我们应该已经知道搭建和使用mvvmlight框架了,下一章节将介绍mvvm下的数据绑定,以下是本章节的源代码下载:

  http://download.csdn.net/source/3246642

本文来自段子林的博客,原文地址:http://blog.csdn.net/duanzilin/archive/2011/05/03/6388593.aspx

  

Mvvm Light Toolkit for WPF/Silverlight系列之搭建mvvmlight开发框架的更多相关文章

  1. MvvmLight学习篇—— Mvvm Light Toolkit for wpf/silverlight系列(导航)

    系列一:看的迷迷糊糊的 一.Mvvm Light Toolkit for wpf/silverlight系列之准备工作 二.Mvvm Light Toolkit for wpf/silverlight ...

  2. Mvvm Light Toolkit 入门

    原文:Mvvm Light Toolkit 入门 前言 之前学习UWP的时候就一直看到有关MVVM的资料但是一直没有系统的去学,最近正好有时间,特地来攻破这个点,顺便学习一下VS与GitHub的链接和 ...

  3. MVVM Light Toolkit使用指南

    原文:MVVM Light Toolkit使用指南 原文地址:  https://blog.csdn.net/ldld1717/article/details/77040077 概述 MVVM Lig ...

  4. How to install MVVM Light Toolkit via NuGet

    Here is how you can install MVVM Light Toolkit  via NuGet in an easy way using only Visual Studio. S ...

  5. WPF基础到企业应用系列7——深入剖析依赖属性(WPF/Silverlight核心)

    一. 摘要 首先圣殿骑士非常高兴这个系列能得到大家的关注和支持.这个系列从七月份開始到如今才第七篇,上一篇公布是在8月2日,掐指一算有二十多天没有继续更新了,最主要原因一来是想把它写好,二来是由于近期 ...

  6. MVVM Light 笔记

    4.关于子视图, MVVMLight Using Two Views:http://www.codeproject.com/Articles/323187/MVVMLight-Using-Two-Vi ...

  7. MVVM Light须要注意的10个问题

    MVVM Light须要注意的10个问题 从使用XAML技术基础開始(实际上并非非常久曾经).我便关注MVVM(Model – View – ViewModel)模式.偶然接触到MVVM Light不 ...

  8. WPF学习12:基于MVVM Light 制作图形编辑工具(3)

    本文是WPF学习11:基于MVVM Light 制作图形编辑工具(2)的后续 这一次的目标是完成 两个任务. 本节完成后的效果: 本文分为三个部分: 1.对之前代码不合理的地方重新设计. 2.图形可选 ...

  9. WPF学习11:基于MVVM Light 制作图形编辑工具(2)

    本文是WPF学习10:基于MVVM Light 制作图形编辑工具(1)的后续 这一次的目标是完成 两个任务. 画布 效果: 画布上,选择的方案是:直接以Image作为画布,使用RenderTarget ...

随机推荐

  1. HTML中Select的使用具体解释

    <html> <head> <SCRIPT LANGUAGE="JavaScript"> <!-- //oSelect 列表的底部加入了一 ...

  2. [React] Using the classnames library for conditional CSS

    Classnames is a simple yet versatile javascript utility that joins CSS class names based on a set of ...

  3. [译]信仰是怎样毁掉程序猿的How religion destroys programmers

    作者原文地址 作者John Sonmez 英文水平不够高,翻译不太准确. 翻译地址:译文 尽管文章是13年的,可是这段时间恰好看到.net开源核心之后,各种java和.net掐架. 语言之争有些牵涉到 ...

  4. QT运行时加载UI文件

      写QT程序里运行时加载UI文件,代码如下: 点击(此处)折叠或打开 #include "keyboard.h" #include <QtUiTools> #incl ...

  5. 多态VI的创建

    比较适合使用多态VI的场合:一个算法会应用到几种不同的数据类型上.比如读写 INI 文件的 VI,它 们既可以读写数值型的数据,也可以读写字符串.布尔等数据类型. 实现多态 VI 之前,一般先实现它的 ...

  6. iOS VoiceOver Programming Guide

    VoiceOver是苹果“读屏”技术的名称,属于辅助功能的一部分.VoiceOver可以读出屏幕上的信息,以帮助盲人进行人机交互. 这项技术在苹果的各个系统中都可以看到,OS X,iOS,watchO ...

  7. Android EventBus

    https://github.com/greenrobot/EventBus onEvent:如果使用onEvent作为订阅函数,那么该事件在哪个线程发布出来的,onEvent就会在这个线程中运行,也 ...

  8. Ubuntu14.04 固定IP

    Ubuntu 固定IP 1. 更改/etc/network/interfaces的内容 1.1 注释掉原来的内容 1.2 添加以下内容 auto eth0 iface eth0 inet static ...

  9. 简单的实现QQ通信功能(四)

    第四部分:主界面的设计及代码 一:效果图及界面设计 1. 效果图: 2. 界面设计: (1)上面显示自己信息用一个PictureBox和两个Label,用来显示自己的头像和昵称备注名. (2)下面用了 ...

  10. 完全用LINUX工作

    http://blog.csdn.net/e6894853/article/details/7881091 下面列出我常用的一些 Linux 程序.一个列表里可能有很多,那是为了方便你来选择,我列出了 ...