MVVM框架搭建
以下是概要的目录结构,其中View,ViewModel,Model正代表的是MVVM的标识。
View:页面window或者UserControl
Model:数据模型对象
ViewModel:与View交互binding,逻辑业务处理。
当然可以根据自己项目的具体情况,再进行拆分,包括业务逻辑,
服务数据分离,日志分离等。

其中主要的两个文件:
ViewModelBase.cs
ViewModel的绑定
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading; namespace Common
{
public abstract class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public virtual void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
} public static class ViewModelBaseEx
{
public static void OnPropertyChanged<T, TProperty>(this T PropetyChangedBase, Expression<Func<T, TProperty>> propertyName)
where T : ViewModelBase
{
var propertyNameExpression = propertyName.Body as MemberExpression;
if (propertyNameExpression != null)
{
if (Dispatcher.CurrentDispatcher.Thread == Thread.CurrentThread)
{
PropetyChangedBase.OnPropertyChanged(propertyNameExpression.Member.Name);
}
else
{
Application.Current.Dispatcher.BeginInvoke(new Action(() =>
{
PropetyChangedBase.OnPropertyChanged(propertyNameExpression.Member.Name);
}));
}
}
}
}
}
事件binding
DeletgateCommand.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input; namespace Common
{
public class DelegateCommand : System.Windows.Input.ICommand
{
public DelegateCommand(Action executeMethod)
: this(executeMethod, null, false)
{
}
public DelegateCommand(Action executeMethod, Func<bool> canExecuteMethod)
: this(executeMethod, canExecuteMethod, false)
{
}
public DelegateCommand(Action executeMethod, Func<bool> canExecuteMethod, bool isAutomaticRequeryDisabled)
{
if (executeMethod == null)
{
throw new ArgumentNullException("executeMethod");
}
_executeMethod = executeMethod;
_canExecuteMethod = canExecuteMethod;
_isAutomaticRequeryDisabled = isAutomaticRequeryDisabled;
}
public bool CanExecute()
{
if (_canExecuteMethod != null)
{
return _canExecuteMethod();
}
return true;
}
public void Execute()
{
if (_executeMethod != null)
{
_executeMethod();
}
}
public bool IsAutomaticRequeryDisabled
{
get
{
return _isAutomaticRequeryDisabled;
}
set
{
if (_isAutomaticRequeryDisabled != value)
{
if (value)
{
CommandManagerHelper.RemoveHandlersFromRequerySuggested(_canExecuteChangedHandlers);
}
else
{
CommandManagerHelper.AddHandlersToRequerySuggested(_canExecuteChangedHandlers);
}
_isAutomaticRequeryDisabled = value;
}
}
}
public void RaiseCanExecuteChanged()
{
OnCanExecuteChanged();
}
protected virtual void OnCanExecuteChanged()
{
CommandManagerHelper.CallWeakReferenceHandlers(_canExecuteChangedHandlers);
}
public event EventHandler CanExecuteChanged
{
add
{
if (!_isAutomaticRequeryDisabled)
{
CommandManager.RequerySuggested += value;
}
CommandManagerHelper.AddWeakReferenceHandler(ref _canExecuteChangedHandlers, value, );
}
remove
{
if (!_isAutomaticRequeryDisabled)
{
CommandManager.RequerySuggested -= value;
}
CommandManagerHelper.RemoveWeakReferenceHandler(_canExecuteChangedHandlers, value);
}
}
bool System.Windows.Input.ICommand.CanExecute(object parameter)
{
return CanExecute();
}
void System.Windows.Input.ICommand.Execute(object parameter)
{
Execute();
}
private readonly Action _executeMethod = null;
private readonly Func<bool> _canExecuteMethod = null;
private bool _isAutomaticRequeryDisabled = false;
private List<WeakReference> _canExecuteChangedHandlers;
}
public class DelegateCommand<T> : System.Windows.Input.ICommand
{
public DelegateCommand(Action<T> executeMethod)
: this(executeMethod, null, false)
{
}
public DelegateCommand(Action<T> executeMethod, Func<T, bool> canExecuteMethod)
: this(executeMethod, canExecuteMethod, false)
{
}
public DelegateCommand(Action<T> executeMethod, Func<T, bool> canExecuteMethod, bool isAutomaticRequeryDisabled)
{
if (executeMethod == null)
{
throw new ArgumentNullException("executeMethod");
}
_executeMethod = executeMethod;
_canExecuteMethod = canExecuteMethod;
_isAutomaticRequeryDisabled = isAutomaticRequeryDisabled;
}
public bool CanExecute(T obj)
{
if (_canExecuteMethod != null)
{
return _canExecuteMethod(obj);
}
return true;
}
public void Execute(T obj)
{
if (_executeMethod != null)
{
_executeMethod(obj);
}
}
public bool IsAutomaticRequeryDisabled
{
get
{
return _isAutomaticRequeryDisabled;
}
set
{
if (_isAutomaticRequeryDisabled != value)
{
if (value)
{
CommandManagerHelper.RemoveHandlersFromRequerySuggested(_canExecuteChangedHandlers);
}
else
{
CommandManagerHelper.AddHandlersToRequerySuggested(_canExecuteChangedHandlers);
}
_isAutomaticRequeryDisabled = value;
}
}
}
public void RaiseCanExecuteChanged()
{
OnCanExecuteChanged();
}
protected virtual void OnCanExecuteChanged()
{
CommandManagerHelper.CallWeakReferenceHandlers(_canExecuteChangedHandlers);
}
public event EventHandler CanExecuteChanged
{
add
{
if (!_isAutomaticRequeryDisabled)
{
CommandManager.RequerySuggested += value;
}
CommandManagerHelper.AddWeakReferenceHandler(ref _canExecuteChangedHandlers, value, );
}
remove
{
if (!_isAutomaticRequeryDisabled)
{
CommandManager.RequerySuggested -= value;
}
CommandManagerHelper.RemoveWeakReferenceHandler(_canExecuteChangedHandlers, value);
}
}
bool System.Windows.Input.ICommand.CanExecute(object parameter)
{
return CanExecute((T)parameter);
}
void System.Windows.Input.ICommand.Execute(object parameter)
{
Execute((T)parameter);
}
private readonly Action<T> _executeMethod = null;
private readonly Func<T, bool> _canExecuteMethod = null;
private bool _isAutomaticRequeryDisabled = false;
private List<WeakReference> _canExecuteChangedHandlers;
}
//采用弱引用,避免内存泄漏
internal class CommandManagerHelper
{
internal static void CallWeakReferenceHandlers(List<WeakReference> handlers)
{
if (handlers != null)
{
// Take a snapshot of the handlers before we call out to them since the handlers
// could cause the array to me modified while we are reading it.
EventHandler[] callees = new EventHandler[handlers.Count];
int count = ;
for (int i = handlers.Count - ; i >= ; i--)
{
WeakReference reference = handlers[i];
EventHandler handler = reference.Target as EventHandler;
if (handler == null)
{
// Clean up old handlers that have been collected
handlers.RemoveAt(i);
}
else
{
callees[count] = handler;
count++;
}
}
// Call the handlers that we snapshotted
for (int i = ; i < count; i++)
{
EventHandler handler = callees[i];
handler(null, EventArgs.Empty);
}
}
}
internal static void AddHandlersToRequerySuggested(List<WeakReference> handlers)
{
if (handlers != null)
{
foreach (WeakReference handlerRef in handlers)
{
EventHandler handler = handlerRef.Target as EventHandler;
if (handler != null)
{
CommandManager.RequerySuggested += handler;
}
}
}
}
internal static void RemoveHandlersFromRequerySuggested(List<WeakReference> handlers)
{
if (handlers != null)
{
foreach (WeakReference handlerRef in handlers)
{
EventHandler handler = handlerRef.Target as EventHandler;
if (handler != null)
{
CommandManager.RequerySuggested -= handler;
}
}
}
}
internal static void AddWeakReferenceHandler(ref List<WeakReference> handlers, EventHandler handler)
{
AddWeakReferenceHandler(ref handlers, handler, -);
}
internal static void AddWeakReferenceHandler(ref List<WeakReference> handlers, EventHandler handler, int defaultListSize)
{
if (handlers == null)
{
handlers = (defaultListSize > ? new List<WeakReference>(defaultListSize) : new List<WeakReference>());
}
handlers.Add(new WeakReference(handler));
}
internal static void RemoveWeakReferenceHandler(List<WeakReference> handlers, EventHandler handler)
{
if (handlers != null)
{
for (int i = handlers.Count - ; i >= ; i--)
{
WeakReference reference = handlers[i];
EventHandler existingHandler = reference.Target as EventHandler;
if ((existingHandler == null) || (existingHandler == handler))
{
// Clean up old handlers that have been collected
// in addition to the handler that is to be removed.
handlers.RemoveAt(i);
}
}
}
}
}
}
这样基本的内容就齐了,简单的MVVM可以实现binding等功能了。
MVVM框架搭建的更多相关文章
- “老坛泡新菜”:SOD MVVM框架,让WinForms焕发新春
火热的MVVM框架 最近几年最热门的技术之一就是前端技术了,各种前端框架,前端标准和前端设计风格层出不穷,而在众多前端框架中具有MVC,MVVM功能的框架成为耀眼新星,比如GitHub关注度很高的Vu ...
- 前端MVVM框架设计及实现(一)
最近抽出点时间想弄个dom模块化的模板引擎,不过现在这种都是MVVM自带的,索性就想自己造轮子写一个简单的MVVM框架了 借鉴的自然还是从正美的avalon开始了,我记得还是去年6月写过一个系列的av ...
- 整合MVVM框架(Prism)
整合MVVM框架(Prism) 我们基础的框架已经搭建起来了,现在整合MVVM框架Prism,在ViewModel做一些逻辑处理,真正把界面设计分离出来. 这样方便我们系统开发分工合作,同时提高系统可 ...
- js架构设计模式——前端MVVM框架设计及实现(一)
前端MVVM框架设计及实现(一) 最近抽出点时间想弄个dom模块化的模板引擎,不过现在这种都是MVVM自带的,索性就想自己造轮子写一个简单的MVVM框架了 借鉴的自然还是从正美的avalon开始了,我 ...
- 【一】Swift 3.0 新浪微博项目实战 -整体框架搭建
最近要接手swift,所以找了个视频跟着做一下实战项目,在此记录一下过程和心得 框架搭建和目录拆分 关键词:MVVM 架构,桥接文件 桥接文件用于引入OC的头文件,Swift就可以正常使用(宏除外). ...
- Unity 游戏框架搭建 (一) 概述
为了重构手头的一款项目,翻出来当时未接触Unity时候收藏的视频<Unity项目架构设计与开发管理>,对于我这种初学者来说全是干货.简单的总结了一下,以后慢慢提炼. 关于Unity的架 ...
- Angular开发实践(一):环境准备及框架搭建
引言 在工作中引入Angular框架将近一年了,在这一年中不断的踩坑和填坑,当然也学习和积累了很多的知识,包括MVVM框架.前后端分离.前端工程化.SPA优化等等.因此想通过Angular开发实践这系 ...
- 迷你MVVM框架 avalonjs 1.3.9发布
本次升级,avalon改进了许多内部方法,大大提升性能,并且带来异步刷新视图的新功能. ms-html内部不再使用异步 head元素中的avalon元素加入ms-skip指令 重构计算属性,现在超级轻 ...
- Unity 游戏框架搭建 2018 (一) 架构、框架与 QFramework 简介
约定 还记得上版本的第二十四篇的约定嘛?现在出来履行啦~ 为什么要重制? 之前写的专栏都是按照心情写的,在最初的时候笔者什么都不懂,而且文章的发布是按照很随性的一个顺序.结果就是说,大家都看完了,都还 ...
随机推荐
- hive-hbase性能问题
华为负责人本来想用这种表来做大数据开发,先前就听前辈讲过性能存在问题.实际开发过程确实存在不少问题.然后放弃换方案去做了. 1.底层meta映射字段问题.默认4000,如果再做修改会涉及到挺多源码. ...
- Redis源码解析:29事务
Redis通过MULTl,EXEC,WATCH,DISCARD等命令来实现事务(transaction)功能. 事务从MULTI命令开始,之后,该客户端发来的其他命令会被排队,客户端发来EXEC命令之 ...
- Liferay 7:Liferay DXP全套教程内附源码
分享是美德 都是英文教程,有不明白的问题可以随时咨询我. http://www.javasavvy.com/liferay-7-hooks-tutorials/
- stream分组
1.根据集合元素中的一个属性值分组 Person p1 = new Person("张三", new BigDecimal("10.0"));Person p2 ...
- 干货来了!2019阿里云合作伙伴峰会SaaS加速器专场回顾合集:嘉宾分享、深度解读
2019年7月26日,在上海举办的阿里云合作伙伴峰会上,阿里云正式发布SaaS生态战略,计划用阿里云的品牌.渠道.资本.方法论.技术加持伙伴,成就亿级营收独角兽. 该生态战略计划招募10家一级SaaS ...
- Django运行错误常见问题及解决方法1
如果不是在JetBrains PyCharm 2017.2里创建的想在JetBrains PyCharm 2017.2里运行.可以在 编辑结构 进行配置正常使用
- 移动端canvas刮刮乐
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta cont ...
- vue-cli3.x正确打包项目,解决静态资源与路由加载无效的问题,history模式下配合使用nginx运行打包后的项目
使用vue-cli3.x正确打包项目,配合nginx运行打包后的内容 vue.config.js module.exports = { publicPath: './',//打包后的位置(如果不设置这 ...
- 数据库迁移工具DBMigration
- 淘宝镜像(CNPM)安装
淘宝镜像安装:开始-运行-填写cmd,回车键确定- 输入"npm install -g cnpm --registry=https://registry.npm.taobao.org&quo ...