首先MVVM设计模式的结构,
Views: 由Window/Page/UserControl等构成,通过DataBinding与ViewModels建立关联;
ViewModels:由一组命令,可以绑定的属性,操作逻辑构成;因为View与ViewModel进行了解耦,我们可以对ViewModel进行Unit Test;
Models:可以是实体对象或者Web服务;
下面通过一个简单的例子,来介绍一些WPF MVVM模式。示例将展示一个图片浏览器,打开图片,放大/缩小图片大小。首先项目结构:
UI:
ViewModelBase(用来实现修改通知):
public classViewModelBase : INotifyPropertyChanged
{public eventPropertyChangedEventHandler PropertyChanged;protected virtual void OnPropertyChanged(stringpropName)
{if(PropertyChanged!=null)
{
PropertyChanged(this, newPropertyChangedEventArgs(propName));
}
}
}
OpenFileCommand:
public classOpenFileCommand : ICommand
{privateMainViewModel _data;publicOpenFileCommand(MainViewModel data)
{
_data=data;
}public eventEventHandler CanExecuteChanged;public bool CanExecute(objectparameter)
{return true;
}public void Execute(objectparameter)
{
OpenFileDialog dialog= new OpenFileDialog() { Filter = "Image Files|*.jpg;*.png;*.bmp;*.gif"};if(dialog.ShowDialog().GetValueOrDefault())
{
_data.ImagePath=dialog.FileName;
}
}
ZoomCommand:
public enumZoomType
{
ZoomIn= 0,
ZoomOut= 1,
Normal= 2}public classZoomCommand : ICommand
{privateMainViewModel _data;publicZoomCommand(MainViewModel data)
{
_data=data;
}public eventEventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested+=value; }
remove { CommandManager.RequerySuggested-=value; }
}public bool CanExecute(objectparameter)
{return _data.ImagePath != null;
}public void Execute(objectparameter)
{
ZoomType type= (ZoomType)Enum.Parse(typeof(ZoomType), (string)parameter, true);switch(type)
{caseZoomType.Normal:
_data.Zoom= 1;break;caseZoomType.ZoomIn:
_data.Zoom*= 1.2;break;caseZoomType.ZoomOut:
_data.Zoom/= 1.2;break;
}
}
}
MainViewModel:
public classMainViewModel : ViewModelBase
{private string_imagePath;public stringImagePath
{get{return_imagePath;
}set{if (_imagePath !=value)
{
_imagePath=value;
OnPropertyChanged("ImagePath");
}
}
}private double _zoom = 1.0;public doubleZoom
{get{return_zoom;
}set{if(_zoom !=value)
{
_zoom=value;
OnPropertyChanged("Zoom");
}
}
}privateICommand _openFileCommand;publicICommand OpenFileCommand
{get { return_openFileCommand; }
}privateZoomCommand _zoomCommand;publicZoomCommand ZoomCommand
{get { return_zoomCommand; }
}publicMainViewModel()
{
_openFileCommand= new OpenFileCommand(this);
_zoomCommand= new ZoomCommand(this);
}
}
下一步我们要做的是将MainViewModel绑定到MainWindow上,我们可以通过下面两种方式绑定:
1. 直接在MainWindow的Code Behind中进行绑定:
publicMainWindow()
{
InitializeComponent();
DataContext= newMainViewModel();
}
2. 在App.xaml后台代码中绑定(将App.xaml中StartupUri="MainWindow.xaml"删除掉):
publicApp()
{
MainWindow window= newMainWindow();
window.DataContext= newMainViewModel();
window.Show();
}
程序运行效果如下:
到此为止,这个简单的示例就算完成了。点击这里下载代码。
感谢您的阅读。