【简介】
1.作者文章:http://www.galasoft.ch/mvvm/
2.可以通过Nuget下载MVVLight
【对比引用文件】
普通WindowsPhone引用
使用MVVMLight的WindowsPhone程序引用
Microsoft.Practices.ServiceLocation:依赖注入机制的服务本地化程序集。该程序集能够通过为依赖注入提供抽象层整合任何适合的依赖注入容器。
Systems.Windows.interactivity:事件,交互
【安装完MVVMLight之后的文件结构】
<Application x:Class="MVVMLight学习.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone" xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:d1p1="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:vm="clr-namespace:MVVMLight学习.ViewModel" d1p1:Ignorable="d" > <!--应用程序资源--> <Application.Resources> <local:LocalizedStrings xmlns:local="clr-namespace:MVVMLight学习" x:Key="LocalizedStrings" /> <vm:ViewModelLocator x:Key="Locator" d:IsDataSource="True" /> </Application.Resources> <Application.ApplicationLifetimeObjects> <!--处理应用程序的生存期事件所需的对象--> <shell:PhoneApplicationService Launching="Application_Launching" Closing="Application_Closing" Activated="Application_Activated" Deactivated="Application_Deactivated" /> </Application.ApplicationLifetimeObjects> </Application>
App.Xaml中使用了ViewModelLocator进行依赖注入,代码如下:
/* In App.xaml: <Application.Resources> <vm:ViewModelLocator xmlns:vm="clr-namespace:MVVMLight学习" 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 MVVMLight学习.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 } } }