WPF入门教程系列(6)之构造器
二、再来说说构造器:
如果使用NuGet安装的是完整的一个是MVVM Light 框架,而非 MVVM Light libraries only的时候,总是会带上ViewModelLocator类,并且生成资源字典并加入到了全局资源中。
所以每次App初始化的时候,就会去初始化ViewModelLocator类。
实际上他就是一个很基本的视图模型注入器。在构造器中把使用到的ViewModel统一注册,并生成单一实例。
然后使用属性把它暴露出来,每当我们访问属性的时候,就会返回相应的ViewModel实例。
/*
In App.xaml:
<Application.Resources>
<vm:ViewModelLocatorTemplate xmlns:vm="clr-namespace:MVVMLightDemo.ViewModel"
x:Key="Locator" />
</Application.Resources>
In the View:
DataContext="{Binding Source={StaticResource Locator}, Path=ViewModelName}"
*/
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Ioc;
using Microsoft.Practices.ServiceLocation;
using MVVMLightDemo.Model;
namespace MVVMLightDemo.ViewModel
{
/// <summary>
/// This class contains static references to all the view models in the
/// application and provides an entry point for the bindings.
/// <para>
/// See http://www.mvvmlight.net
/// </para>
/// </summary>
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>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance",
"CA1822:MarkMembersAsStatic",
Justification = "This non-static member is needed for data binding purposes.")]
public MainViewModel Main
{
get
{
return ServiceLocator.Current.GetInstance<MainViewModel>();
}
}
/// <summary>
/// Cleans up all the resources.
/// </summary>
public static void Cleanup()
{
}
}
}
注意的是,这边把MVVMLight 自带的SimpleIoc作为默认的服务提供者,它是个简易的注入框架。
为了统一化,并且在设计的时候可以看到看到ViewModel的数据,这边用ServiceLocator 又将SimpleIoc包裹了一层。
上面我们写了一个Hello World,这时候就可以用这种方式改装了。具体的改装参考https://www.cnblogs.com/wzh2010/p/6285990.html
当然如果想修改界面上显示的内容可以修改ViewModel中构造函数的初始化内容。