MVVM Light組成
目前的框架就兩個庫文件:GalaSoft.MvvmLight庫和GalaSoft.MvvmLight.Extras庫。
GalaSoft.MvvmLight庫
ViewModelBase:View Model的基礎類,MVVM中VM的實現。
Messenger:用於ViewModel和View之間傳遞的消息,注意系統的GalaSoft.MvvmLight.Messaging命名空間下已經預定義了一些常使用的消息處理類,如DialogMessage、NotificationMessageAction、NotificationMessageWithCallback等。
Command:命令,RelayCommand,用於和界面元素的響應處理綁定。
GalaSoft.MvvmLight.Extras庫
EventToCommand:使用XAML 綁定Command,Expression4中使用
DispatcherHelper:處理多線程
MVVM Light安裝和使用(Silverlight為例)
GalaSoft.MvvmLight.Binaries.V3.zip
解壓到系統的Program files目錄
GalaSoft.MvvmLight.Templates.V3.VS10.zip
將其中的ItemTemplates ProjectTemplates下的Silverlight內容拷貝到對應的
C:\Users\Administrator\Documents\Visual Studio 2010\Templates下
此時New Project是可以選擇Silverlight下的MVVM light模板,不過這個模板也是比較簡單的
一般項目使用方法:
1、 添加GalaSoft.MvvmLight.SL4.dll GalaSoft.MvvmLight.Extras.SL4.dll引用
2、 在App.xaml中加入ViewModelLocator, 當然如何使用代碼或則MEF實現View和ViewModel之間的綁定,這個也不需要
xmlns:vm="clr-namespace:MvvmLight1.ViewModel"
<vm:ViewModelLocator x:Key="Locator d:IsDataSource="True" />
3、 添加ViewModel、View
此時:ViewModel中:加入Command實現、發送消息和View 傳遞信息
View中:綁定數據、綁定Command、注冊消息、ICleanup實現ViewModel清理注冊消息清理、界面和交互設計
至於View和ViewModel之間的初始化關聯可以使用ViewModelLocator.cs的形式建立和綁定【這個形式還是有些麻煩】,當然也可以使用MEF等IOC實現自動注入。
View中綁定ViewModel可以使用DataContext="{Binding Main, Source={StaticResource Locator}}",也可以使用代碼實現綁定[此處的Locator就是在App.xaml聲明的]
MVVM Light實例
消息注冊 |
一般在View中注冊以響應ViewModel中消息,當然也可以在別處注冊 Messenger.Default.Register(this, OnReadOnlyIssueMessage); Messenger.Default.Register<Brush>(this, true, m => BackgroundBrush = m); |
消息發送 |
Messenger.Default.Send(new CommandMessage(Notifications.NotifyShutdown)); Messenger.Default.Send<Brush, MainViewModel>(savedSettings.ApplicationBackgroundBrush); |
Command定義 |
public RelayCommand ShutdownCommand { get; private set; } public MainViewModel() { if (IsInDesignMode) { } else { ShutdownCommand = new RelayCommand(ShutdownService.RequestShutdown); } } RemoveFileCommand = new RelayCommand<Data.Web.File>(g => this.OnRemoveFileCommand(g), g => g != null); |
Command綁定 |
<Button Content="Shut" Command="{Binding Path= ShutdownCommand }" /> … Command="{Binding Path=RemoveFileCommand}" CommandParameter="{Binding SelectedItem, ElementName=listBox_Files}" |
ICLeanup MEF |
public partial class AllIssues : UserControl, ICleanup { public AllIssues() { InitializeComponent(); if (!ViewModelBase.IsInDesignModeStatic) { // Use MEF To load the View Model CompositionInitializer.SatisfyImports(this); } } [Import(ViewModelTypes.AllIssuesViewModel)] public object ViewModel { set { DataContext = value; } } public void Cleanup() { // call Cleanup on its ViewModel ((ICleanup)this.DataContext).Cleanup(); // call Cleanup on IssueEditor this.issueEditor.Cleanup(); // Cleanup itself Messenger.Default.Unregister(this); } |
DispatcherHelper |
源代碼中GalaSoft.MvvmLight.Test (SL).csproj TestDispatcherHelper.cs有詳細內容 |
ViewModel |
從ViewModelBase繼承實現視圖對應的類 |