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>
运行结果如下:
MVVMLight学习笔记(四)---RelayCommand初探的更多相关文章
- C#可扩展编程之MEF学习笔记(四):见证奇迹的时刻
前面三篇讲了MEF的基础和基本到导入导出方法,下面就是见证MEF真正魅力所在的时刻.如果没有看过前面的文章,请到我的博客首页查看. 前面我们都是在一个项目中写了一个类来测试的,但实际开发中,我们往往要 ...
- IOS学习笔记(四)之UITextField和UITextView控件学习
IOS学习笔记(四)之UITextField和UITextView控件学习(博客地址:http://blog.csdn.net/developer_jiangqq) Author:hmjiangqq ...
- java之jvm学习笔记四(安全管理器)
java之jvm学习笔记四(安全管理器) 前面已经简述了java的安全模型的两个组成部分(类装载器,class文件校验器),接下来学习的是java安全模型的另外一个重要组成部分安全管理器. 安全管理器 ...
- Learning ROS for Robotics Programming Second Edition学习笔记(四) indigo devices
中文译著已经出版,详情请参考:http://blog.csdn.net/ZhangRelay/article/category/6506865 Learning ROS for Robotics Pr ...
- Typescript 学习笔记四:回忆ES5 中的类
中文网:https://www.tslang.cn/ 官网:http://www.typescriptlang.org/ 目录: Typescript 学习笔记一:介绍.安装.编译 Typescrip ...
- ES6学习笔记<四> default、rest、Multi-line Strings
default 参数默认值 在实际开发 有时需要给一些参数默认值. 在ES6之前一般都这么处理参数默认值 function add(val_1,val_2){ val_1 = val_1 || 10; ...
- muduo网络库学习笔记(四) 通过eventfd实现的事件通知机制
目录 muduo网络库学习笔记(四) 通过eventfd实现的事件通知机制 eventfd的使用 eventfd系统函数 使用示例 EventLoop对eventfd的封装 工作时序 runInLoo ...
- python3.4学习笔记(四) 3.x和2.x的区别,持续更新
python3.4学习笔记(四) 3.x和2.x的区别 在2.x中:print html,3.x中必须改成:print(html) import urllib2ImportError: No modu ...
- Go语言学习笔记四: 运算符
Go语言学习笔记四: 运算符 这章知识好无聊呀,本来想跨过去,但没准有初学者要学,还是写写吧. 运算符种类 与你预期的一样,Go的特点就是啥都有,爱用哪个用哪个,所以市面上的运算符基本都有. 算术运算 ...
- 零拷贝详解 Java NIO学习笔记四(零拷贝详解)
转 https://blog.csdn.net/u013096088/article/details/79122671 Java NIO学习笔记四(零拷贝详解) 2018年01月21日 20:20:5 ...
随机推荐
- 深度解析 Lucene 轻量级全文索引实现原理
一.Lucene简介 1.1 Lucene是什么? Lucene是Apache基金会jakarta项目组的一个子项目: Lucene是一个开放源码的全文检索引擎工具包,提供了完整的查询引擎和索引引擎, ...
- 求数组的子数组之和的最大值III(循环数组)
新的要求:一维数组改成循环数组,只是涉及简单算法,只是拿了小数做测试 想法:从文件读取数组,然后新建数组,将文件读取的数组在新数组中做一下连接,成为二倍长度的数组,然后再遍历,将每次遍历的子数组的和存 ...
- CSAPP:bomblab
BOMBLAB实验总结 CSAPP实验BOMB,很头疼,看不懂,勉强做完了. 答案是这样的: Border relations with Canada have never been better. ...
- 在R中使用Keras和TensorFlow构建深度学习模型
一.以TensorFlow为后端的Keras框架安装 #首先在ubuntu16.04中运行以下代码 sudo apt-get install libcurl4-openssl-dev libssl-d ...
- nacos Connection refused (Connection refused)
记录一次"异常bug",具体信息如下.主要是记录一下处理过程,可能口水话比较多,如果想看结果,直接往后拉即可. 最后一行 起初,运维同事找到我,跟我说程序出问题了,系统升级,一直连 ...
- 【贪心+排序】排队接水 luogu-1223
题目描述 有n个人在一个水龙头前排队接水,假如每个人接水的时间为Ti,请编程找出这n个人排队的一种顺序,使得n个人的平均等待时间最小. 分析 注意要开longlong AC代码 #include &l ...
- SpringCloud升级之路2020.0.x版-2.微服务框架需要考虑的问题
本系列为之前系列的整理重启版,随着项目的发展以及项目中的使用,之前系列里面很多东西发生了变化,并且还有一些东西之前系列并没有提到,所以重启这个系列重新整理下,欢迎各位留言交流,谢谢!~ 上图中演示了一 ...
- user-agent浏览器标识集合
user_agent_list = [ "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; AcooBrowser; .NET ...
- BSTestRunner增加历史执行记录展示和重试功能
之前对于用例的失败重试,和用例的历史测试记录存储展示做了很多的描述呢,但是都是基于各个项目呢,不方便使用,为了更好的使用,我们对这里进行抽离,抽离出来一个单独的模块,集成到BSTestRunner中, ...
- Wireshark过滤器详解
Wireshark过滤器详解 1.Wireshark主要提供两种主要的过滤器 捕获过滤器:当进行数据包捕获时,只有那些满足给定的包含/排除表达式的数据包会被捕获 显示过滤器:该过滤器根据指定的表达式用 ...