好久不写WPF和MVVM,新建一个Project后,想起来ViewModelBase和RelayCommand没有。以下Code摘自MSDN上的Article:Patterns - WPF Apps With The Model-View-ViewModel Design Pattern中附带的示例代码:

Class ViewModelBase :

using System;
using System.ComponentModel;
using System.Diagnostics; namespace DemoApp.ViewModel
{
/// <summary>
/// Base class for all ViewModel classes in the application.
/// It provides support for property change notifications
/// and has a DisplayName property. This class is abstract.
/// </summary>
public abstract class ViewModelBase : INotifyPropertyChanged, IDisposable
{
#region Constructor protected ViewModelBase()
{
} #endregion // Constructor #region DisplayName /// <summary>
/// Returns the user-friendly name of this object.
/// Child classes can set this property to a new value,
/// or override it to determine the value on-demand.
/// </summary>
public virtual string DisplayName { get; protected set; } #endregion // DisplayName #region Debugging Aides /// <summary>
/// Warns the developer if this object does not have
/// a public property with the specified name. This
/// method does not exist in a Release build.
/// </summary>
[Conditional("DEBUG")]
[DebuggerStepThrough]
public void VerifyPropertyName(string propertyName)
{
// Verify that the property name matches a real,
// public, instance property on this object.
if (TypeDescriptor.GetProperties(this)[propertyName] == null)
{
string msg = "Invalid property name: " + propertyName; if (this.ThrowOnInvalidPropertyName)
throw new Exception(msg);
else
Debug.Fail(msg);
}
} /// <summary>
/// Returns whether an exception is thrown, or if a Debug.Fail() is used
/// when an invalid property name is passed to the VerifyPropertyName method.
/// The default value is false, but subclasses used by unit tests might
/// override this property's getter to return true.
/// </summary>
protected virtual bool ThrowOnInvalidPropertyName { get; private set; } #endregion // Debugging Aides #region INotifyPropertyChanged Members /// <summary>
/// Raised when a property on this object has a new value.
/// </summary>
public event PropertyChangedEventHandler PropertyChanged; /// <summary>
/// Raises this object's PropertyChanged event.
/// </summary>
/// <param name="propertyName">The property that has a new value.</param>
protected virtual void OnPropertyChanged(string propertyName)
{
this.VerifyPropertyName(propertyName); PropertyChangedEventHandler handler = this.PropertyChanged;
if (handler != null)
{
var e = new PropertyChangedEventArgs(propertyName);
handler(this, e);
}
} #endregion // INotifyPropertyChanged Members #region IDisposable Members /// <summary>
/// Invoked when this object is being removed from the application
/// and will be subject to garbage collection.
/// </summary>
public void Dispose()
{
this.OnDispose();
} /// <summary>
/// Child classes can override this method to perform
/// clean-up logic, such as removing event handlers.
/// </summary>
protected virtual void OnDispose()
{
} #if DEBUG
/// <summary>
/// Useful for ensuring that ViewModel objects are properly garbage collected.
/// </summary>
~ViewModelBase()
{
string msg = string.Format("{0} ({1}) ({2}) Finalized", this.GetType().Name, this.DisplayName, this.GetHashCode());
System.Diagnostics.Debug.WriteLine(msg);
}
#endif #endregion // IDisposable Members
}
}

Class RelayCommand:

using System;
using System.Diagnostics;
using System.Windows.Input; namespace DemoApp
{
/// <summary>
/// A command whose sole purpose is to
/// relay its functionality to other
/// objects by invoking delegates. The
/// default return value for the CanExecute
/// method is 'true'.
/// </summary>
public class RelayCommand : ICommand
{
#region Fields readonly Action<object> _execute;
readonly Predicate<object> _canExecute; #endregion // Fields #region Constructors /// <summary>
/// Creates a new command that can always execute.
/// </summary>
/// <param name="execute">The execution logic.</param>
public RelayCommand(Action<object> execute)
: this(execute, null)
{
} /// <summary>
/// Creates a new command.
/// </summary>
/// <param name="execute">The execution logic.</param>
/// <param name="canExecute">The execution status logic.</param>
public RelayCommand(Action<object> execute, Predicate<object> canExecute)
{
if (execute == null)
throw new ArgumentNullException("execute"); _execute = execute;
_canExecute = canExecute;
} #endregion // Constructors #region ICommand Members [DebuggerStepThrough]
public bool CanExecute(object parameter)
{
return _canExecute == null ? true : _canExecute(parameter);
} public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
} public void Execute(object parameter)
{
_execute(parameter);
} #endregion // ICommand Members
}
}

是为之记。
Alva Chien
2016.6.20

C# II: Class ViewModelBase and RelayCommand in MVVM的更多相关文章

  1. 【MVVM Light】新手初识MVVM,你一看就会

    一.前言 作为一个初入软件业的新手,各种设计模式与框架对我是眼花缭乱的.所以当我接触到这些新知识的时候就希望自己能总结几个步骤,以便更好更方便的在日常工作中进行使用. MVVM顾名思义就是Model- ...

  2. 说不尽的MVVM(2) – MVVM初体验

    知识预备 阅读本文,我假定你已经具备以下知识: C#.WPF基础知识 了解Lambda表达式和TPL 对事件驱动模型的了解 知道ICommand接口 发生了什么 某程序员接到一个需求,编写一个媒体渲染 ...

  3. [uwp]MVVM之MVVMLight,一个登录注销过程的简单模拟

    之前学MVVM,从ViewModelBase,RelayCommand都是自己瞎写,许多地方处理的不好,接触到MVVMLigth后,就感觉省事多了. 那么久我现在学习MVVMLight的收获,简单完成 ...

  4. MVVM开发模式简单实例MVVM Demo

    本文主要是翻译Rachel Lim的一篇有关MVVM模式介绍的博文 A Simple MVVM Example 并具体给出了一个简单的Demo(原文是以WPF开发的,对于我自己添加或修改的一部分会用红 ...

  5. MVVM与Backbone demo

    MVVM https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93viewmodel

  6. 说不尽的MVVM(4) – 发号施令的Command

    知识预备 阅读本文,我假定你具备以下知识: C# WPF基础知识 知道WPF的命令 WPF相对WinForm加了一种Command的机制,对用户的操作进行更加灵活的处理,相信很多朋友知道并用过Rout ...

  7. 在UWP中实现自己的MVVM设计模式

    其实写这篇博文的时候我是拒绝的,因为这牵扯到一个高大上的东西——"框架".一说起这个东西,很多朋友就感觉有点蒙了,尤其是编程新手.因为它不像在代码里面定义一个变量那么显而易见,它是 ...

  8. DevExpress MVVM<1>

    DevExpress MVVM 概念 模型 -定义数据和您的业务逻辑. 视图 -指定UI,包括绑定到ViewModel中的属性和命令的所有可视元素(按钮,标签,编辑器等). ViewModel-连接模 ...

  9. Messenger

    Messenger Mvvm提倡View和ViewModel的分离,View只负责数据的显示,业务逻辑都尽可能放到ViewModel中, 保持View.xaml.cs中的简洁(没有任何代码,除了构造函 ...

随机推荐

  1. Java中的接口(什么是接口,接口的好处,具体的使用)

    1.什么是接口? 官方概述: 在java语言中,接口不是类,而是对类的一组需求描述,这些类要遵从接口描述的统一格式进行定义. 这种技术主要用来描述类具有什么功能,而并不给出每个类的具体实现. Bala ...

  2. PHP array_change_key_case

    (PHP 4 >= 4.2.0, PHP 5, PHP 7) 1.函数的作用 : 改变数组所有键值的大小写: 2.参数: 1)array : 应用的数组: 2)case  : 指定转换为大写或者 ...

  3. 两分钟让你明白Go中如何继承

    最近在重构代码的时候,抽象了大量的接口.也使用这些抽象的接口做了很多伪继承的操作,极大的减少了代码冗余,同时也增加了代码的可读性. 然后随便搜了一下关于Go继承的文章,发现有的文章的代码量过多,并且代 ...

  4. 2、Struts2开始深入

    一.Struts2的配置文件加载顺序 1 .进入过滤器[StrutsPrepareAndExecuteFilter]跟代码,可以看到对应的文件加载顺序 进入StrtsPrepareAndExecute ...

  5. linux文档、目录相关

    linux中常用文档的目录规则: /var 存放经常变化的文件 /home 普通用户家目录 /home/xiaoliu 小刘同学的用户家目录 /etc 存放配置文件的目录 /etc/my.cnf my ...

  6. Linux Centos7 基于Docker 搭建 Nexus私服搭建

    创建Blob Stores[本地文件存储目录,统一管理] 1.设置名称和工作路径: ps[注意事项]: 1.storage name:自定义名称 2.storage path:存储路径,默认[/nex ...

  7. Leetcode(10)正则表达式匹配

    Leetcode(10)正则表达式匹配 [题目表述]: 给定一个字符串 (s) 和一个字符模式 (p).实现支持 '.' 和 '*' 的正则表达式匹配. '.' 匹配任意单个字符. '*' 匹配零个或 ...

  8. The usage of Markdown---引用

    目录 1. 序言 2. 引用与嵌套引用 3. 列表中的引用 更新时间:209.09.14 1. 序言   在本篇,我们来仔细谈一下Markdown的引用. 2. 引用与嵌套引用   在Markdown ...

  9. recovery模式差分(增量)升级小结

    最近在做recovery模式下的升级,简单的总结一下. 先说说recovery模式,他是个升级小系统,有单独的kernel,通过特定的系统命令就可以进入到此系统中,选择进入正常系统的kernel还是r ...

  10. 四元数(Quaternion)

    从应用角度说一下unity Quaternion,Quaternion是四元数,百度相关资料可能找到的都是一些大牛给你搞个矩阵云云,给你讲解四元数.在此只是从应用角度讲一讲.最简单理解四元数对应一个向 ...