好久不写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. Web安全之URL跳转科普

    跳转无非是传递过来的参数未过滤或者过滤不严,然后直接带入到跳转函数里去执行. 0x01 JS js方式的页面跳转1.window.location.href方式 <script language ...

  2. PHP in_array

    1.函数的作用:判读一个元素是否在一个数组存在 2.函数的参数: @param mixed $needle @param array $array 3. if it’s ok to use isset ...

  3. PHP krsort

    1.什么都不想说了,干么没事放那么悲伤的歌呢?回忆里我还是对代码懵懵懂懂的无知青年!也许不是青年,只是少年... <?php $arr = [ 1 => 'Zhangbiyu', 2 =& ...

  4. Spring Boot2 系列教程(十四)CORS 解决跨域问题

    今天和小伙伴们来聊一聊通过CORS解决跨域问题. 同源策略 很多人对跨域有一种误解,以为这是前端的事,和后端没关系,其实不是这样的,说到跨域,就不得不说说浏览器的同源策略. 同源策略是由 Netsca ...

  5. [JZOJ100026]【NOIP2017提高A组模拟7.7】图

    Description 有一个n个点n条边的有向图,每条边为<i,f(i),w(i)>,意思是i指向f(i)的边权为w(i)的边,现在小A想知道,对于每个点的si和mi. si:由i出发经 ...

  6. React学习系列之(1)简单的demo(React脚手架)

    1.什么是React? React是一个一个声明式,高效且灵活的用于构建用户界面的JavaScript库.React 起源于 Facebook 的内部项目,用来架设 Instagram 的网站,并于 ...

  7. xss姿势利用

    1.定位页面可以出现xss的位置 可能会出现联合点利用 一个页面多个存储位置或者一个页面多个参数联合利用 例如输入xss 查看页面源码页面里有多个xss 或者多个参数显示 可以利用 需要注意的是有的是 ...

  8. LeetCode初级算法--排序和搜索01:第一个错误的版本

    LeetCode初级算法--排序和搜索01:第一个错误的版本 搜索微信公众号:'AI-ming3526'或者'计算机视觉这件小事' 获取更多算法.机器学习干货 csdn:https://blog.cs ...

  9. jmeter-定时器使用

    在一般性能测试过程中,往往在前一个请求之后等待一段时间再执行下一个请求,这时会用到定时器. 以下列举常用的3中: 1.固定定时器: 2.

  10. SQL挑战一 : 查找最晚入职员工的所有信息

    以上数据库表: CREATE TABLE `employees` ( `emp_no` int(11) NOT NULL, `birth_date` date NOT NULL, `first_nam ...