WPF内建的COMMAND是GOF 提出的23种设计模式中,命令模式的实现。

本文是WPF学习07:MVVM 预备知识之数据绑定的后续,将说明实现COMMAND的三个重点:ICommand  CommandManager InputBindings

COMMAND简介

一般情况我们应用设计如下,一个个控件的各类Handler直接关心了如何实现具体的应用逻辑。

借助COMMAND,我们将具体实现的应用逻辑放在COMMAND中实现,控件只需要绑定相应的COMMAND,而无需关心应用逻辑,从而实现界面与应用逻辑的解耦。

WPF内建的COMMAND除了提供了逻辑解耦外,还可以用来实现控件使能管理、命令的历史记录(使操作可撤销)。

本文将介绍如何在MVVM下运用COMMAND,以及控件的使能管理。历史记录功能将在下篇学习笔记中再介绍。


例子

由CheckBox 管理Command是否可以被执行,Ctrl + A与按键被按均能执行同样的业务逻辑。

XAML代码:

<Window x:Class="Commands.CommandBlog"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="CommandBlog" Height="300" Width="300">
<Window.InputBindings>
<KeyBinding Key="A" Modifiers="Control" Command="{Binding NewFile}"></KeyBinding>
</Window.InputBindings>
<StackPanel Background="White">
<Button Command="{Binding NewFile}">New file</Button>
<CheckBox IsChecked="{Binding NewFileEnable}" HorizontalAlignment="Center">New file Function Enable</CheckBox>
</StackPanel>
</Window>
 

界面部分后台代码,只需要配置DataContext即可:

public partial class CommandBlog : Window
{
public CommandBlog()
{
InitializeComponent();
DataContext = new CommandBlogViewModel();
}
}

CommandBlogViewModel:

class CommandBlogViewModel:INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public ICommand NewFile
{
get;
private set;
} public CommandBlogViewModel()
{
NewFile = new NewFileCommand(this);
} private Boolean newFileEnable; public Boolean NewFileEnable
{
get { return newFileEnable; }
set
{
newFileEnable = value;
if (PropertyChanged != null)
PropertyChanged.Invoke(this, new PropertyChangedEventArgs("NewFileEnable"));
}
}
}

NewFileCommand:

class NewFileCommand : ICommand
{
private CommandBlogViewModel commandBlogViewModel; public NewFileCommand(CommandBlogViewModel commandBlogViewModel)
{
this.commandBlogViewModel = commandBlogViewModel;
} public bool CanExecute(object parameter)
{
return this.commandBlogViewModel.NewFileEnable;
} public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
} public void Execute(object parameter)
{
MessageBox.Show("New");
}
}

ICommand

// Summary:
// Occurs when changes occur that affect whether or not the command should execute.
event EventHandler CanExecuteChanged; // Summary:
// Defines the method that determines whether the command can execute in its
// current state.
bool CanExecute(object parameter);
// Summary:
// Defines the method to be called when the command is invoked.
void Execute(object parameter);

CanExecute与Execute的意思都很明显,可以在刚才的例子中看出来。这里重点介绍一下如何给它们传参。

我们可以通过设置CommandParameter向两者传参:
    例子:

<!--主窗体起名为MainWindow-->
<Button Command="{Binding NewFile}" CommandParameter="{Binding ElementName=MainWindow}">New file</Button>

public void Execute(object parameter)
{
var inputElement = parameter as IInputElement;
if (inputElement!= null)
{
var pos = Mouse.GetPosition(inputElement);
}
}

CommandManager

为了使WPF能够自动识别CanExecute的变化,我们需要手动对CanExecuteChanged加以下代码:

public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}

InputBindings

当我们希望可以自定义命令的输入映射时,需要用到InputBindings:

例子:

<Window.InputBindings>
<KeyBinding Key="A" Modifiers="Control" Command="{Binding NewFile}"></KeyBinding>
<KeyBinding Key="C" Modifiers="Control" Command="{Binding CopyContent}"></KeyBinding>
<KeyBinding Key="V" Modifiers="Control" Command="{Binding PasteContent}"></KeyBinding>
<KeyBinding Key="F1" Modifiers="Control" Command="{Binding HelpPrompt}"></KeyBinding>
</Window.InputBindings>

WPF学习08:MVVM 预备知识之COMMAND的更多相关文章

  1. WPF ContextMenu 在MVVM模式中绑定 Command及使用CommandParameter传参

    原文:WPF ContextMenu 在MVVM模式中绑定 Command及使用CommandParameter传参 ContextMenu无论定义在.cs或.xaml文件中,都不继承父级的DataC ...

  2. WPF学习07:MVVM 预备知识之数据绑定

    MVVM是一种模式,而WPF的数据绑定机制是一种WPF内建的功能集,两者是不相关的. 但是,借助WPF各种内建功能集,如数据绑定.命令.数据模板,我们可以高效的在WPF上实现MVVM.因此,我们需要对 ...

  3. WPF学习之路(六)Command

    在WPF中,命令绑定机制是相比于事件更高级的概念,把应用程序的功能划分为多个任务,任务由多种途径触发. 应用Command Binding使代码更符合MVVM模式(Model-View-ViewMod ...

  4. 《视觉SLAM十四讲》学习日志(一)——预备知识

    SLAM简介 : SLAM是 Simultaneous Localization and Mapping 的缩写,中文译作 " 同时定位与地图构建 ".它是指搭载特定传感器的主题, ...

  5. WPF学习09:数据绑定之 Binding to List Data

    从WPF学习03:Element Binding我们可以实现控件属性与控件属性的绑定. 从WPF学习07:MVVM 预备知识之数据绑定 我们可以实现控件属性与自定义对象属性的绑定. 而以上两个功能在实 ...

  6. IP地址和子网划分学习笔记之《预备知识:进制计数》

    一.序:IP地址和子网划分学习笔记开篇 只要记住你的名字,不管你在世界的哪个地方,我一定会去见你.——新海诚 电影<你的名字> 在我们的日常生活中,每个人的名字对应一个唯一的身(敏)份(感 ...

  7. 自动化预备知识上&&下--Android自动化测试学习历程

    章节:自动化基础篇——自动化预备知识上&&下 主要讲解内容及笔记: 一.需要具备的能力: 测试一年,编程一年,熟悉并掌握业界自动化测试工具(monkey--压力测试.monkeyrun ...

  8. WPF学习11:基于MVVM Light 制作图形编辑工具(2)

    本文是WPF学习10:基于MVVM Light 制作图形编辑工具(1)的后续 这一次的目标是完成 两个任务. 画布 效果: 画布上,选择的方案是:直接以Image作为画布,使用RenderTarget ...

  9. WPF学习10:基于MVVM Light 制作图形编辑工具(1)

    图形编辑器的功能如下图所示: 除了MVVM Light 框架是一个新东西之外,本文所涉及内容之前的WPF学习0-9基本都有相关介绍. 本节中,将搭建编辑器的界面,搭建MVVM Light 框架的使用环 ...

随机推荐

  1. AngularJS自己定义标签加入回调函数eval()

    function helloworld(name){ console.log("hello!!!!!"+name) } var name="zhangsan"; ...

  2. [数据集]新浪微博数据集MicroblogPCU

    数据集下载地址:下载 摘要:MicroblogPCU是从新浪微博採集到的.它能够被用于研究机器学习方法和社会关系研究. 这个数据集被原作者用于探索微博中的spammers(发送垃圾信息的人).他们的d ...

  3. Codeforces 104C Cthulhu dfs暴力 || 点双连通缩点

    题目链接:点击打开链接 题意: 给定n个点m条边的无向图 问图中是否存在 有且仅有一个简单环和一些树,且这些树的root都在这个简单环上. 瞎写了个点双. . == #include <stdi ...

  4. properties文件读取配置信息

    public static void main(String[] args){ String printerName=""; String path = "C:\\Bar ...

  5. Apsara Clouder专项技能认证:实现调用API接口 (笔记)

  6. 普通用户无法登陆SSH问题

    Linux正常情况下普通用户是可以登陆SSH的,除非系统管理员作了修改,如果没有修改的情况无法登陆可以尝试以下方法解决: 步骤/方法 1 查看 /etc/ssh/sshd_config文件 发现 ro ...

  7. 剑指Offer面试题11(Java版):数值的整数次方

    题目:实现函数double Power(double base,int exponent),求base的exponent次方.不得使用库函数,同一时候不须要考虑大数问题 1.自以为非常easy的解法: ...

  8. bzoj1934: [Shoi2007]Vote 善意的投票&&bzoj2768:[JLOI2010]冠军调查

    get到新姿势,最小割=最大流,来个大佬的PPT 这道题的做法是将st和1的xpy连,0的xpy和ed连,xpy之间jy连双向边,然后呢答案就是最小割. #include<cstdio> ...

  9. echo 到 stderr

    This question is old, but you could do this, which facilitates reading: >&2 echo "error& ...

  10. BZOJ_2081_[Poi2010]Beads_哈希

    BZOJ_2081_[Poi2010]Beads_哈希 Description Zxl有一次决定制造一条项链,她以非常便宜的价格买了一长条鲜艳的珊瑚珠子,她现在也有一个机器,能把这条珠子切成很多块(子 ...