前面几个章节,主要介绍了,在不引用MvvmLight框架的情况下,利用WPF自身的特性;如何实现界面与数据,以及业务逻辑的解耦;解耦后,我们将代码整理到不同的程序集,便于管理;最终整理结果如下:
为了更方便地使用Mvvm设计模式,我们引用MvvmLight框架; 如何安装框架,参见《MvvmLight(1) 介绍》
使用MvvmLight框架时,MvvmLight会自动创建 ViewModelLocator类,所以我们把ViewModel程序集中自定义的ViewModelLocator删除,再通过Nuget引用框架;
引用成功后,MvvmLight框架自动为我们创建了ViewModel文件夹,含MainViewModel.cs 和ViewModelLocator.cs; MainViewModel是继承自ViewModelBase类,主要是实现Mvvm框架的ViewModel部分;ViewModelLocator类主要是方便我们管理ViewModel实例;
MvvmLight关键类
ObservableObject
实现了INotifyPropertyChanged接口;其添加了检测属性名称是否正确等功能;引用MvvmLight后,我们的自定义类可以继承自该类,然后通过调用RaisePropertyChanged(PropertyName)就可以通知属性更改了
下面是我们修改后的自定义数据模型
public class Account:ObservableObject
{
private string name;
private string phone;
public Account()
{
name = "Wangjianjun";
phone = "123456";
}
public Account(string accountName )
{
this.name = accountName;
}
public string Name {
get => name;
set {
name = value;
RaisePropertyChanged(()=> Name);
//通知发生改变的属性是哪一个
//PropertyChanged.Invoke(this,new PropertyChangedEventArgs("Name"));
}}
public string Phone { get => phone;
set {
phone = value;
RaisePropertyChanged(() => Phone);
} }
/// <summary>
/// 继承自INotifyPropertyChanged
/// </summary>
//public event PropertyChangedEventHandler PropertyChanged;
}
ViewModelBase
继承了ObservableObject类和ICleanup接口
下面是我们修改后的mainWindowViewModel
public class MainWindowViewModel:ViewModelBase
{
private Account _Data = new Account();
public Account AccountData
{
get {
return _Data;
}
set
{
_Data = value;
RaisePropertyChanged(()=> AccountData);
//PropertyChanged.Invoke(this, new PropertyChangedEventArgs("AccountData"));
}
}
//public event PropertyChangedEventHandler PropertyChanged;
}
ViewModelLocator
ViewModel 通过统一注册和提取ViewModel实例,实现对ViewModel的统一管理;通过ViewModelLocator将ViewModel暴露给各个界面;
下面是我们修改后的ViewModelLocator代码
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>();
SimpleIoc.Default.Register<MainWindowViewModel>();
}
public MainWindowViewModel MainWindows
{
get
{
return ServiceLocator.Current.GetInstance<MainWindowViewModel>();
}
}
public MainViewModel Main
{
get
{
return ServiceLocator.Current.GetInstance<MainViewModel>();
}
}
public static void Cleanup()
{
// TODO Clear the ViewModels
}
}
MvvmLight框架引入完成