MvvMLight学习心得二
2012-12-13 22:44 爱研究源码的javaer 阅读(696) 评论(0) 编辑 收藏 举报隔了几个月了,这几个月忙的时候忙,出差的时候辗转各地,广州,佛山,山东,没有静下心来研究一些开源项目,自己感
觉十分的苦恼和纠结,还是能够安静下来研究些技术比较舒畅一点。最近也在学习C++,今后一定要把C++的心得也分享出
来以便交流和学习。可能过些时间会把博客迁至GitHub上去闲话说回来,今天我们继续上次遗留下来的话题,先来看下MvvMLight的项目总体结构,首先我打开
中的GalaSoft.MvvmLight (NET35).sln解决方案来看下:
看到在GalaSoft.MvvmLight(NET35)下有个ICleanUp.cs,这个文件就存放了上回我们讲到的ViewModelBase.cs中实
现的ICleanUp接口。
namespace GalaSoft.MvvmLight { /// <summary> /// Defines a common interface for classes that should be cleaned up, /// but without the implications that IDisposable presupposes. An instance /// implementing ICleanup can be cleaned up without being /// disposed and garbage collected. /// </summary> //// [ClassInfo(typeof(ViewModelBase))] public interface ICleanup { /// <summary> /// Cleans up the instance, for example by saving its state, /// removing resources, etc... /// </summary> void Cleanup(); } }
看到这个接口里其实就一个方法CleanUp。注释也很详细:清楚实例,比如保存实例的状态,移出资源等等。。。
让我们来看看ViewModelBase类里是怎么实现ICleanUp接口的:
/// <summary> /// Unregisters this instance from the Messenger class. /// <para>To cleanup additional resources, override this method, clean /// up and then call base.Cleanup().</para> /// </summary> public virtual void Cleanup() { MessengerInstance.Unregister(this); }
他是通过该类的MessagerInstance属性
/// <summary> /// Gets or sets an instance of a <see cref="IMessenger" /> used to /// broadcast messages to other objects. If null, this class will /// attempt to broadcast using the Messenger's default instance. /// </summary> protected IMessenger MessengerInstance { get { return _messengerInstance ?? Messenger.Default; } set { _messengerInstance = value; } }
(其实也就是IMessager接口实例)的Unregister方法传递该实例来清除资源
的。可以重写该方法,再调用该类的的CleanUp方法。所以可以看见定义虚方法是多么的重要。
从CleanUp方法调用IMessager这也可以看出Messager在MvvmLight举足轻重的地位。下回我们先通过实例来看下
Messager是如何使用的。