C# II: Class ViewModelBase and RelayCommand in MVVM
好久不写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的更多相关文章
- 【MVVM Light】新手初识MVVM,你一看就会
一.前言 作为一个初入软件业的新手,各种设计模式与框架对我是眼花缭乱的.所以当我接触到这些新知识的时候就希望自己能总结几个步骤,以便更好更方便的在日常工作中进行使用. MVVM顾名思义就是Model- ...
- 说不尽的MVVM(2) – MVVM初体验
知识预备 阅读本文,我假定你已经具备以下知识: C#.WPF基础知识 了解Lambda表达式和TPL 对事件驱动模型的了解 知道ICommand接口 发生了什么 某程序员接到一个需求,编写一个媒体渲染 ...
- [uwp]MVVM之MVVMLight,一个登录注销过程的简单模拟
之前学MVVM,从ViewModelBase,RelayCommand都是自己瞎写,许多地方处理的不好,接触到MVVMLigth后,就感觉省事多了. 那么久我现在学习MVVMLight的收获,简单完成 ...
- MVVM开发模式简单实例MVVM Demo
本文主要是翻译Rachel Lim的一篇有关MVVM模式介绍的博文 A Simple MVVM Example 并具体给出了一个简单的Demo(原文是以WPF开发的,对于我自己添加或修改的一部分会用红 ...
- MVVM与Backbone demo
MVVM https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93viewmodel
- 说不尽的MVVM(4) – 发号施令的Command
知识预备 阅读本文,我假定你具备以下知识: C# WPF基础知识 知道WPF的命令 WPF相对WinForm加了一种Command的机制,对用户的操作进行更加灵活的处理,相信很多朋友知道并用过Rout ...
- 在UWP中实现自己的MVVM设计模式
其实写这篇博文的时候我是拒绝的,因为这牵扯到一个高大上的东西——"框架".一说起这个东西,很多朋友就感觉有点蒙了,尤其是编程新手.因为它不像在代码里面定义一个变量那么显而易见,它是 ...
- DevExpress MVVM<1>
DevExpress MVVM 概念 模型 -定义数据和您的业务逻辑. 视图 -指定UI,包括绑定到ViewModel中的属性和命令的所有可视元素(按钮,标签,编辑器等). ViewModel-连接模 ...
- Messenger
Messenger Mvvm提倡View和ViewModel的分离,View只负责数据的显示,业务逻辑都尽可能放到ViewModel中, 保持View.xaml.cs中的简洁(没有任何代码,除了构造函 ...
随机推荐
- Pillow模块图片生成
0825自我总结 Pillow模块图片生成 一.模块安装 pip3 install pillow 二.模块的载入 import PIL 三.django结合img标签生成图片 img.html < ...
- python selenium自动化常用关键字
工具安装: 1.安装python 2.安装selenium库(dos命令下进入selenium-2.53.2存放路径,执行pip install selenium-2.53.2) 3.将浏览器驱动放到 ...
- Java8系列 (一) Lambda表达式
函数式编程 在介绍Lambda表达式之前, 首先需要引入另一个概念, 函数式编程. 函数式编程是一种编程范式, 也就是如何编写程序的方法论.它的核心思想是将运算过程尽量写成一系列嵌套的函数调用,关注的 ...
- Linux对目录操作命令
cd /home 进入 '/ home' 目录 cd .. 返回上一级目录 cd ../.. 返回上两级目录 cd 进入个人的主目录 cd ~u ...
- webpack知识分享
webpack 4 webpack 四大核心概念: 入口(entry) // 打包入口 输出(output) : 打包后输出的位置配置 loader : loader 让 webpack 能够去处理 ...
- C加加学习之路 2——两招让你成为牛X的T型人才
有个小伙伴在微信上问我: 我刚工作半年,有时候对于Java的发展方向有点迷茫,Java的范围是在是太广了,我有时候会不知道从哪开始入手,我想问一下,您有什么好的建议吗? 我理解这位朋友的问题是:工作中 ...
- 微信公众号 访问403问题,样式错乱,js失效
我服了,还是那个微信公众号小项目. 这个项目用的是ssm+velocity 问题的是,有时候页面加载会乱,js,css都加载不出来. 这个问题也是很久了,前几天开会,那个甲方医院很不开心,说是要找下家 ...
- javascript获取坐标/滚动/宽高/距离
坐标(鼠标/触摸) event.screenX 鼠标/触摸,相对于显示屏的X坐标 event.screenY 鼠标/触摸,相对于显示屏的Y坐标 event.clientX 鼠标/触摸,相对于浏览器视口 ...
- index.html
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title&g ...
- 2018.8.10 python中的迭代器
主要内容: 1.函数名的使用 2.闭包 3.迭代器 一.函数名的运用 函数名是一个变量,但他是一个特殊的变量,与括号配合可执行函数的变量. 1.函数名的内存地址 def func(): print(' ...