MVVM模式是Model-View-ViewModel的简称。
1.Model层就是实体层,利用vs带的向项目中添加数据模型和向模型中添加代码生成项(自跟踪实体),可以快速方便的从数据库创建实体。
这个也不是MVVM重点关注的。
2.View层就是界面表现层,他包含展现给用户的具体页面,MVVM实现了表现层和业务逻辑层的彻底分离,这也是他的优势,更加方便了团队合作开发。
采用MVVM模式做的项目,经常会发现界面后面几乎零代码,开始觉得很神奇,连一个事件都没有却实现了N多功能,这应该是归功于.Net平台的新特性,依赖属性。
3.ViewModel层就是传统三层架构中的业务逻辑层,具体的业务逻辑就是在这里,这一层负责连接Model和View。这一层我认为是MVVM的核心。
View和ViewModel通过两种属性连接在一起:数据属性和命令属性,为此我们需要为ViewModel准备两类:
1.实现了INotifyPropertyChanged接口的类,假定我们给他起名叫BaseViewModel,则大致代码如下:
public class BaseViewModel: INotifyPropertyChanged
{ public event PropertyChangedEventHandler PropertyChanged;public void RaisePropertyChanged(string propertyName)
{ if (this.PropertyChanged != null) { this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } }他将是所有ViewModel类的基类。
2.实现了ICommand接口的类,假定给他起名为DelegateCommand,则大致代码如下:
public class DelegateCommand : ICommand
{ public bool CanExecute(object parameter) { if (CanExecuteFunc != null) { return CanExecuteFunc(parameter); } return false; }public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{ if (this.ExecuteAction != null) { this.ExecuteAction(parameter); } }public Action<object> ExecuteAction { get; set; }
public Func<object, bool> CanExecuteFunc { get; set; }
}我们现在假设有这么一个实体:
public Class People
{
private string _name;
public string Name
{
get{return _name;}
set{ _name=value;}
}
}
还有一个界面,上面有个Button还有个TextBox,要实现的功能就是 点击Button就将People实体一个对象的Name属性改为Jim并显示到TextBox上。
ViewModel层中添加一个TestViewModel类:
class TestViewModel : BaseViewModel
{ private People _people1; public People People1 { get { return _people1; } set { this._people1 = value; this.RaisePropertyChanged("People1"); } } public DelegateCommand ButtonCommand { get; set; } private void ButtonClick(object parameter) { this.People1.Name = "Jim"; }public TestViewModel()
{ this.ButtonCommand = new DelegateCommand(); this.ButtonCommand.ExecuteAction = new Action<object>(this.ButtonClick); } }然后在在那个界面的Xaml文件为window标签添加资源(在这之前要先引入TestViewModel所在的名称空间,我起名为vm):
<Window.Resources>
<vm:TestViewModel x:Key="ViewModel"/> </Window.Resources>然后在Button和TextBox所在标签上添加:
<Grid DataContext="{Binding Source={StaticResource ResourceKey=ViewModel}, Path=MyProperty}">
最后一步,在那个界面的Xaml文件中找到TextBox标签,修改成这样:
<TextBoxText="{Binding Name}"/>