一、概述
在MVVM Light框架中,主要通過命令綁定來進行事件的處理。
WPF中,命令是通過實現 ICommand 接口創建的。 ICommand 公開了兩個方法(Execute 及 CanExecute)和一個事件(CanExecuteChanged)。
在MVVM Light框架中,RelayCommand類實現了ICommand 接口,用於完成命令綁定。
通過RelayCommand類的構造函數傳入Action類型的Execute委托和Func<bool>類型的CanExecute委托,CanExecute委托用於表示當前命令是否可以執行,Execute委托則表示執行當前命令對應的方法。
通過命令綁定,解耦了View和ViewModel的行為交互,將視圖的顯示和業務邏輯分開。比如我們對界面上的某個按鈕進行命令綁定,當點擊按鈕的時候,實際上進行操作是在對應的ViewModel下的所綁定的方法中執行的。
二、Demo
我們模擬以下場景:
界面上有一個添加用戶的按鈕,一個輸入用戶信息的TextBox,一個用於顯示添加后結果Label,一個CheckBox。
按鈕使用RelayCommand進行綁定,CheckBox用於控制命令的可用性。

1 using GalaSoft.MvvmLight; 2 3 namespace MvvmLightDemo1.Model 4 { 5 public class WelcomeModel : ObservableObject 6 { 7 private string welcomeMsg; 8 public string WelcomeMsg 9 { 10 get { return welcomeMsg; } 11 set { welcomeMsg = value; RaisePropertyChanged(() => WelcomeMsg); } 12 } 13 } 14 15 }

1 using CommonServiceLocator; 2 using GalaSoft.MvvmLight.Ioc; 3 4 namespace MvvmLightDemo1.ViewModel 5 { 6 /// <summary> 7 /// This class contains static references to all the view models in the 8 /// application and provides an entry point for the bindings. 9 /// </summary> 10 public class ViewModelLocator 11 { 12 /// <summary> 13 /// Initializes a new instance of the ViewModelLocator class. 14 /// </summary> 15 public ViewModelLocator() 16 { 17 ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default); 18 SimpleIoc.Default.Register<MainViewModel>(); 19 } 20 21 public MainViewModel Main 22 { 23 get 24 { 25 return ServiceLocator.Current.GetInstance<MainViewModel>(); 26 } 27 } 28 29 public static void Cleanup() 30 { 31 // TODO Clear the ViewModels 32 } 33 } 34 }
1 using GalaSoft.MvvmLight; 2 using GalaSoft.MvvmLight.CommandWpf; 3 using MvvmLightDemo1.Model; 4 using System.Windows.Input; 5 6 namespace MvvmLightDemo1.ViewModel 7 { 8 public class MainViewModel : ViewModelBase 9 { 10 private WelcomeModel welcomeModel; 11 public WelcomeModel WelcomeModel 12 { 13 get { return welcomeModel; } 14 set { welcomeModel = value; RaisePropertyChanged(() => WelcomeModel); } 15 } 16 /// <summary> 17 /// Initializes a new instance of the MainViewModel class. 18 /// </summary> 19 public MainViewModel() 20 { 21 WelcomeModel = new WelcomeModel() { WelcomeMsg = "Welcome to MVVMLight World!" }; 22 } 23 24 private string userList = "Mary"; 25 26 public string UserList 27 { 28 get { return userList; } 29 set 30 { 31 userList = value; 32 RaisePropertyChanged(); 33 } 34 } 35 private string user = ""; 36 37 public string User 38 { 39 get { return user; } 40 set { user = value; } 41 } 42 private bool isCanAddUser; 43 44 public bool IsCanAddUser 45 { 46 get { return isCanAddUser; } 47 set { isCanAddUser = value; } 48 } 49 50 #region Command 51 private RelayCommand addUserCommand; 52 53 public RelayCommand AddUserCommand 54 { 55 get 56 { 57 if (addUserCommand == null) 58 { 59 addUserCommand = new RelayCommand(AddUser, () => { return IsCanAddUser; }); 60 } 61 return addUserCommand; 62 } 63 set { addUserCommand = value; } 64 } 65 private void AddUser() 66 { 67 UserList = UserList + " " + User; 68 } 69 #endregion 70 71 } 72 }

1 <Window x:Class="MvvmLightDemo1.MainWindow" 2 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 3 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 4 xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 5 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 6 xmlns:local="clr-namespace:MvvmLightDemo1" 7 mc:Ignorable="d" 8 Title="MVVMLIghtDemo1" Height="350" Width="525" Background="#FF699DC1"> 9 <Window.DataContext> 10 <Binding Path="Main" Source="{StaticResource Locator}"></Binding> 11 </Window.DataContext> 12 <Grid> 13 <StackPanel > 14 <TextBlock Text="{Binding WelcomeModel.WelcomeMsg}" FontSize="28" Foreground="#FFBB4913" HorizontalAlignment="Center"/> 15 <StackPanel Orientation="Horizontal" Visibility="Collapsed"> 16 <Label Content="修改信息:" VerticalContentAlignment="Center" FontSize="20" Foreground="#FFC55D21"></Label> 17 <TextBox Text="{Binding Path=WelcomeModel.WelcomeMsg,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" FontSize="20" Foreground="#FFBB4913"/> 18 <Button Content="LostFocus" Background="#FF22A658"></Button> 19 </StackPanel> 20 21 <StackPanel Orientation="Horizontal"> 22 <Label Content="UserList:" VerticalContentAlignment="Center" FontSize="20" Foreground="#FFC55D21"></Label> 23 <Label Content="{Binding Path=UserList,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" FontSize="20" Foreground="#FFBB4913"/> 24 </StackPanel> 25 <StackPanel Orientation="Horizontal"> 26 <Label Content="UserName:" VerticalContentAlignment="Center" FontSize="20" Foreground="#FFC55D21"></Label> 27 <TextBox Width="200" Text="{Binding User, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"></TextBox> 28 <Button Content="AddUser" Command="{Binding AddUserCommand}"></Button> 29 <CheckBox Content="IsCanAdd" VerticalAlignment="Center" FontSize="16" IsChecked="{Binding IsCanAddUser, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"></CheckBox> 30 </StackPanel> 31 32 </StackPanel> 33 <StackPanel VerticalAlignment="Top" HorizontalAlignment="Center" > 34 35 </StackPanel> 36 </Grid> 37 </Window>
運行結果如下: