一、概述

在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>

运行结果如下:

MVVMLight学习笔记(四)---RelayCommand初探的更多相关文章

  1. C#可扩展编程之MEF学习笔记(四):见证奇迹的时刻

    前面三篇讲了MEF的基础和基本到导入导出方法,下面就是见证MEF真正魅力所在的时刻.如果没有看过前面的文章,请到我的博客首页查看. 前面我们都是在一个项目中写了一个类来测试的,但实际开发中,我们往往要 ...

  2. IOS学习笔记(四)之UITextField和UITextView控件学习

    IOS学习笔记(四)之UITextField和UITextView控件学习(博客地址:http://blog.csdn.net/developer_jiangqq) Author:hmjiangqq ...

  3. java之jvm学习笔记四(安全管理器)

    java之jvm学习笔记四(安全管理器) 前面已经简述了java的安全模型的两个组成部分(类装载器,class文件校验器),接下来学习的是java安全模型的另外一个重要组成部分安全管理器. 安全管理器 ...

  4. Learning ROS for Robotics Programming Second Edition学习笔记(四) indigo devices

    中文译著已经出版,详情请参考:http://blog.csdn.net/ZhangRelay/article/category/6506865 Learning ROS for Robotics Pr ...

  5. Typescript 学习笔记四:回忆ES5 中的类

    中文网:https://www.tslang.cn/ 官网:http://www.typescriptlang.org/ 目录: Typescript 学习笔记一:介绍.安装.编译 Typescrip ...

  6. ES6学习笔记<四> default、rest、Multi-line Strings

    default 参数默认值 在实际开发 有时需要给一些参数默认值. 在ES6之前一般都这么处理参数默认值 function add(val_1,val_2){ val_1 = val_1 || 10; ...

  7. muduo网络库学习笔记(四) 通过eventfd实现的事件通知机制

    目录 muduo网络库学习笔记(四) 通过eventfd实现的事件通知机制 eventfd的使用 eventfd系统函数 使用示例 EventLoop对eventfd的封装 工作时序 runInLoo ...

  8. python3.4学习笔记(四) 3.x和2.x的区别,持续更新

    python3.4学习笔记(四) 3.x和2.x的区别 在2.x中:print html,3.x中必须改成:print(html) import urllib2ImportError: No modu ...

  9. Go语言学习笔记四: 运算符

    Go语言学习笔记四: 运算符 这章知识好无聊呀,本来想跨过去,但没准有初学者要学,还是写写吧. 运算符种类 与你预期的一样,Go的特点就是啥都有,爱用哪个用哪个,所以市面上的运算符基本都有. 算术运算 ...

  10. 零拷贝详解 Java NIO学习笔记四(零拷贝详解)

    转 https://blog.csdn.net/u013096088/article/details/79122671 Java NIO学习笔记四(零拷贝详解) 2018年01月21日 20:20:5 ...

随机推荐

  1. Java开源协同办公项目:数据中心,自定义查询语句使用教程

    O2OA提供的数据管理中心,可以让用户通过配置的形式完成对数据的汇总,统计和数据分组展现,查询和搜索数据形成列表数据展现.也支持用户配置独立的数据表来适应特殊的业务的数据存储需求.本文主要介绍如何在O ...

  2. 家庭账本开发day04

    对之前的构架进行修改,对成员类新加属性余额,在进行账单的新增时 ,对余额进行相应的修改.并且对账单类加入属性:id方便之后的查询和 删除操作

  3. Ubuntu18.04 安装opensips,实现局域网内sip语音视频通话

    Ubuntu18.04直接安装opensips 本人实践亲测有效,用docker安装opensips尝试多次均无法连接mysql数据库,故舍弃,直接在主机上安装opensips 部分内容参考自:htt ...

  4. ORM研究3 - odoo fields常用的字段属性

    之前我们已经讲解了odoo ORM中的一些对字段常用的API操作方法,今天我们继续研究一下Odoo orm中字段的一些通用属性字段的使用,学会它们可以为自己创建数据映射并使用有更好的帮助. 通用字段属 ...

  5. 【算法学习笔记】概率与期望DP

    本文学习自 Sengxian 学长的博客 之前也在CF上写了一些概率DP的题并做过总结 建议阅读完本文再去接着阅读这篇文章:Here 前言 单纯只用到概率的题并不是很多,从现有的 OI/ACM 比赛中 ...

  6. React组件三大属性之 refs

    React组件三大属性之 refs refs属性 1) 组件内的标签都可以定义ref属性来标识自己 a. <input type="text" ref={input => ...

  7. 微信小程序云开发-云函数-初始化云函数环境

    一.新建云函数文件夹 新建的云函数文件夹,命名为cloud,该文件夹一定要与pages文件夹同级.此时该文件夹的前面没有云朵的标识.  二.配置project.config.json文件 在proje ...

  8. 八大排序算法~冒泡排序【加变量flag的作用】

    八大算法~冒泡排序[加变量flag的作用] 1,冒泡排序思想:从第一个数开始找,要把大数"排除在外"~为大数找后座.(从小到大排序哈) 外层循环~需要放后的大数个数: 内循环~从第 ...

  9. Leetcode 春季打卡活动 第一题:225. 用队列实现栈

    Leetcode 春季打卡活动 第一题:225. 用队列实现栈 Leetcode 春季打卡活动 第一题:225. 用队列实现栈 解题思路 这里用了非常简单的思路,就是在push函数上做点操作,让队头总 ...

  10. Spring事务管理中的配置文件(三)

    在开发中,遇到了sql语句报错,但是并没有回滚的情况. 经过几天的排查,终于找到了事务没有回滚的原因. 原来的项目用的是informix的数据库,原来针对事务回滚的机制都是好用的.我本地用的是mysq ...