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中的简洁(没有任何代码,除了构造函 ...
随机推荐
- PMP(第六版)中的各种矩阵表格
- opencv::霍夫圆变换
霍夫圆检测原理 从平面坐标到极坐标转换三个参数 假设平面坐标的任意一个圆上的点,转换到极坐标中: 处有最大值,霍夫变换正是利用这个原理实现圆的检测. cv::HoughCircles 因为霍夫圆检测对 ...
- pytest6-Fixture finalization / executing teardown code(使用yield来实现)
Fixture finalization / executing teardown code By using a yield statement instead of return, all the ...
- 00jmeter安装相关
1.官网下载安装包:http://jmeter.apache.org/ 下载最新版本: 2.将下载后的zip文件解压 3. jdk与jmeter的环境变量配置(以下变量如果没有则新建,如果已存在则直接 ...
- LevelDB性能测试|Golang调用LevelDB
LevelDB性能测试|Golang调用LevelDB 不同方式使用压力测试 用ssdb,TCP连接方式调用,底层存储levelDB 直接调用Cgo的levelDB (必须保证串行) 直接调用Gola ...
- office visio 2019 下载激活
安装 下载 office ed2k://|file|cn_office_professional_plus_2019_x86_x64_dvd_5e5be643.iso|3775004672|1E4FF ...
- Charles抓包工具的使用(一)
前提:charles的说明 Charles其实是一款代理服务器,通过过将自己设置成系统(电脑或者浏览器)的网络访问代理服务器,然后截取请求和请求结果达到分析抓包的目的.该软件是用Java写的,能够在W ...
- Java基础(十)接口(interface)
1.接口的概念 在Java中,接口不是类,而是对类的一组需求描述,这些类要遵从接口描述. 例如:Array类中的sort方法可以对对象数组进行排序,但要求满足下列前提:对象所属的类必须实现了Compa ...
- MongoDB一次节点宕机引发的思考(源码剖析)
目录 简介 日志分析 副本集 如何实现 Failover 心跳的实现 electionTimeout 定时器 业务影响评估 参考链接 声明:本文同步发表于 MongoDB 中文社区,传送门: http ...
- Xbim.GLTF源码解析(三):Builder类
原创作者:flowell,转载请标明出处:https://www.cnblogs.com/flowell/p/10838706.html IFC提取转换成GLTF的逻辑在Builder类中, Buil ...