• MVVMLight学习笔记(四)RelayCommand初探(转)


    一、概述

     在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>
    复制代码

    运行结果如下:

  • 相关阅读:
    [转载红鱼儿]delphi 实现微信开发(1)
    Devexpress VCL Build v2013 vol 14.1.3 发布
    [翻译]LSP程序的分类
    睡眠不好
    LuaStudio 9.27 去10分钟退出暗桩板
    vs2012 提示 未能正确加载 "Visual C++ Language Manager Package" 包 的解决办法
    岁月蹉跎
    重新安装系统之前备份
    运动会
    乱思
  • 原文地址:https://www.cnblogs.com/lzjsky/p/15681706.html
Copyright © 2020-2023  润新知