MVVM --- 实现多层级通知
引言
在实际开发场景中,当ViewModel内的一个属性是一个 ObservableCollection<T> 或者是一个多层级 class 的时候,有可能有的需求需要 ObservableCollection<T>内的元素的子属性或多层级 class 的子属性,甚至子属性的子属性,变化,需要通知到ViewModel,该怎么做呢?
例如我有一个设置功能模块,十几个模型,一两百个属性参数,模型之间是2~3层的嵌套关系,最后得到一个大模型表示Model,我想要在子属性的值变化的是通知到ViewModel,记录日志或其他操作。
现有的MVVM框架,例如 MVVMLight ,Prism , 我好像都没有找到这样的功能,如果有更好的方案或实现,烦请告之。
现在手动实现一个这样的辅助类。接下来看一下实现过程:
INotifyHolder接口
先定义 INotifyHolder 接口,用于通知 HolderViewModel ,有属性变化了。
namespace MvvmNoticeHolderLib
{
public interface INotifyHolder
{
void AfterPropertyChangedNotified(object sender, string info);
}
}
NoticeFlagAttribute特性
定义 NoticeFlagAttribute 特性,用于标记哪些属性是需要在变化时通知到 HolderViewModel 的。
namespace MvvmNoticeHolderLib
{
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public class NoticeFlagAttribute : Attribute
{
public string Name { get; set; } = string.Empty;
public Type Type { get; set; }
public NoticeFlagAttribute(string names, Type type)
{
Name = names;
Type = type;
}
}
}
NotifyHolder的Binding管理器
namespace MvvmNoticeHolderLib
{
public class NotifyHolderBindingManager
{
private static T BindSlaveProperty<T>(T source, object root)
{
try
{
if (source != null)
{
var type = source.GetType();
var properties = type.GetProperties();
var NoticeFlags = type.GetCustomAttributes<NoticeFlagAttribute>();
if (NoticeFlags != null && NoticeFlags.Count() > 0)
{
foreach (var noticeFlag in NoticeFlags)
{
PropertyInfo info = properties.SingleOrDefault(x => x.Name == noticeFlag.Name);
if (info != null)
{
BindProperty(source, root, info);
}
}
}
}
return source;
}
catch (Exception ex)
{
return source;
}
}
public static T BindSelfProperty<T>(T root)
{
try
{
if (root != null)
{
var type = root.GetType();
var properties = type.GetProperties();
var NoticeFlags = type.GetCustomAttributes<NoticeFlagAttribute>();
if (NoticeFlags != null && NoticeFlags.Count() > 0)
{
foreach (var noticeFlag in NoticeFlags)
{
PropertyInfo info = properties.SingleOrDefault(x => x.Name == noticeFlag.Name);
if (info != null)
{
BindSlaveProperty(root, root);
var tmp = info.GetValue(root);
if (root is INotifyPropertyChanged notify)
{
notify.PropertyChanged += (sender, e) =>
{
if (NoticeFlags.Any(t => t.Name == e.PropertyName))
{
var senderType = sender.GetType();
PropertyInfo senderProperty = senderType.GetProperty(e.PropertyName);
BindProperty(sender, sender, senderProperty);
}
};
}
}
}
}
}
return root;
}
catch (Exception)
{
return root;
}
}
private static void BindProperty<T>(T source, object root, PropertyInfo info)
{
if (info.PropertyType.IsGenericType && info.PropertyType.GetGenericTypeDefinition() == typeof(ObservableCollection<>))
{
var tmp = info.GetValue(source);
if (tmp != null && tmp is INotifyCollectionChanged notifyCollectionChanged)
{
notifyCollectionChanged.CollectionChanged += (sender, e) =>
{
if (e.NewItems != null && e.NewItems.Count > 0)
{
BindSlaveProperty(e.NewItems[0], root);
if (e.NewItems[0] != null && e.NewItems[0] is INotifyPropertyChanged notify)
{
if (root is INotifyHolder notifyHolder)
{
notify.PropertyChanged += (s, e) =>
{
notifyHolder.AfterPropertyChangedNotified(s, info.Name + "." + e.PropertyName + "发生了变化");
};
}
}
}
};
var arr = (IEnumerable<object>)tmp;
foreach (var item in arr)
{
if (item is INotifyPropertyChanged notify && root is INotifyHolder notifyHolder)
{
BindSlaveProperty(item, root);
notify.PropertyChanged += (sender, e) =>
{
notifyHolder.AfterPropertyChangedNotified(sender, info.Name + "." + e.PropertyName + "发生了变化");
};
}
}
}
}
else if (info.PropertyType.GetInterfaces().Contains(typeof(INotifyPropertyChanged)))
{
var tmp = info.GetValue(source);
if (tmp != null && tmp is INotifyPropertyChanged notify)
{
BindSlaveProperty(tmp, root);
if (root is INotifyHolder notifyHolder)
{
notify.PropertyChanged += (sender, e) =>
{
notifyHolder.AfterPropertyChangedNotified(sender, info.Name + "." + e.PropertyName + "发生了变化");
};
}
}
}
}
}
}
这个类就是实现这个功能的核心,其主要原理是,通过 NoticeFlagAttribute 特性,获取你要绑定的属性,然后 监控你要绑定的属性的 INotifyPropertyChanged 的PropertyChanged 事件或者是 INotifyCollectionChanged 的 CollectionChanged事件,最后通知到 HolderViewModel 中,若子属性有多层级关系,可以多层级中每个层级使用 NoticeFlagAttribute 特性,标记你想要监控的属性,然后Binding管理器通过递归方式依次绑定好,就实现了多层级的监控通知到 HolderViewModel 中。
我已将Demo发布到github,Readme.md中有使用说明。
github仓库地址
MVVM --- 实现多层级通知的更多相关文章
- CommunityToolkit.Mvvm8.1 消息通知(4)
本系列文章导航 https://www.cnblogs.com/aierong/p/17300066.html https://github.com/aierong/WpfDemo (自我Demo地址 ...
- 说不尽的MVVM(3) – 从通知属性说起
上篇我们体验了一个从事件处理程序到MVVM程序的转变,在最后也留下了一个问题:RaisePropertyChanged的原理是什么?今天我们来一探究竟. 通过上节做的小例子我们知道,仅仅修改ViewM ...
- android MVC && MVP && MVVM分析和对比
相关:http://www.cnblogs.com/wytiger/p/5305087.html 出处http://blog.csdn.net/self_study,对技术感兴趣的同鞋加群544645 ...
- iOS开发项目之MVC与MVVM
MVC MVC,Model-View-Controller,我们从这个古老而经典的设计模式入手.采用 MVC 这个架构的最大的优点在于其概念简单,易于理解,几乎任何一个程序员都会有所了解,几乎每一所计 ...
- ReactiveCocoa 和 MVVM 入门 (转)
翻译自ReactiveCocoa and MVVM, an Introduction. 文中引用的 Gist 可能无法显示.为了和谐社会, 请科学上网. MVC 任何一个正经开发过一阵子软件的人都熟悉 ...
- 【长篇高能】ReactiveCocoa 和 MVVM 入门
翻译自ReactiveCocoa and MVVM, an Introduction. 文中引用的 Gist 可能无法显示.为了和谐社会, 请科学上网. MVC 任何一个正经开发过一阵子软件的人都熟悉 ...
- 【转】伟大的RAC和MVVM入门(一)
原文:http://www.sprynthesis.com/2014/12/06/reactivecocoa-mvvm-introduction/ 翻译自ReactiveCocoa and MVV ...
- javascript基础修炼(9)——MVVM中双向数据绑定的基本原理
开发者的javascript造诣取决于对[动态]和[异步]这两个词的理解水平. 一. 概述 1.1 MVVM模型 MVVM模型是前端单页面应用中非常重要的模型之一,也是Single Page Appl ...
- 基于vue实现一个简单的MVVM框架(源码分析)
不知不觉接触前端的时间已经过去半年了,越来越发觉对知识的学习不应该只停留在会用的层面,这在我学jQuery的一段时间后便有这样的体会. 虽然jQuery只是一个JS的代码库,只要会一些JS的基本操作学 ...
- 使用MVVM设计模式构建WPF应用程序
使用MVVM设计模式构建WPF应用程序 本文是翻译大牛Josh Smith的文章,WPF Apps With The Model-View-ViewModel Design Pattern,译者水平有 ...
随机推荐
- Redis 数据库配置与应用
Redis 是一个key-value存储系统.Redis是一个开源的使用ANSI C语言编写.遵守BSD协议.支持网络.可基于内存亦可持久化的日志型.Key-Value数据库,并提供多种语言的API. ...
- 给textarea添加行号,textarea使用代码风格的一些思考
背景 项目有个需求是 在textarea中编辑脚本并显示为代码风格样式,显示行号: textarea显示行号 思路: 1.监听textarea内容变化,执行一个change函数,解析内容里面有多少个换 ...
- unordered_map模拟实现|STL源码剖析系列|开散列
博主很久没有更新过STL源码剖析这个系列的文章了,主要是因为大部分STL常用的容器,博主都已经发过文章了,今天博主带着大家把哈希表也模拟实现一下. 前言 那么这里博主先安利一下一些干货满满的专栏啦! ...
- 树莓派4B改造成云桌面客户端,连接DoraCloud免费版
Raspberry Pi(树莓派) 是为学习计算机编程教育而设计的只有信用卡大小的微型电脑,自问世以来受众多计算机发烧友和创客的追捧,曾经一"派"难求. DoraCloud是一款多 ...
- Exadata刷机快速参考
本文以Exadata X8 HC 1/4 rack为例,介绍整个Exadata刷机的步骤. 我理解刷机最关键的就两大步骤:第一步是所有机器刷OS,第二步是使用OEDA一键刷机.至于其它所有工作都是在为 ...
- RSAToken 的签名算法 SHA256withRSA、数字签名
数字签名的意义,看下百科:数字签名sign可不是对数据的加密和解密,而是生成签名和验证签名. https://baike.baidu.com/item/%E6%95%B0%E5%AD%97%E7%AD ...
- Raise发现
procedure TForm2.Button1Click(Sender: TObject); var MyWoKao: string; I: Integer; begin try try I := ...
- 树莓派安装freeswitch
树莓派版本: Raspberry Pi 4B 操作系统 : Ubuntu Server 20.04_x64 freeswitch版本 : 1.10.3 1.下载freeswitch源代码 wget h ...
- NC24158 [USACO 2015 Jan G]Moovie Mooving
题目链接 题目 题目描述 Bessie is out at the movies. Being mischievous as always, she has decided to hide from ...
- 基于keras的胶囊网络(CapsNet)
1 简介 胶囊网络(CapsNet)由 Hinton 于2017年10月在<Dynamic Routing Between Capsules>中提出,目的在于解决 CNN 只能提取特征,而 ...