Basic MVVM Base class / INotifyPropertyChanged implementation

<div class="entry-meta"><span class="posted-on"><a href="https://onewindowsdev.com/2017/07/21/basic-mvvm-base-class-inotifypropertychanged-implementation/" rel="bookmark"><time class="entry-date published updated" datetime="2017-07-21T23:25:32+00:00">July 21, 2017</time></a></span><span class="byline"> <span class="author vcard"><a class="url fn n" href="https://onewindowsdev.com/author/bluechrism/">bluechrism</a></span></span></div>
	<h1 class="entry-title">
	Basic MVVM Base class / INotifyPropertyChanged implementation	</h1>

<div class="entry-content">
	<p>A while back, (OK, a long while back), <a href="https://onewindowsdev.com/?p=32">I promised an article on how to create a MMVM view model base class</a>.&nbsp; This class will implement the INotifyPropertyChanged interface, and add some common sugar on top of it to make it really easy to use.</p>

In all project types that use XAML, you can bind items in the UI to properties in the view model. The purpose of INotifyPropertyChanged is to notify those binding of when the underlying property changes so the updated values can be pulled in. It has one item, an event called PropertyChanged. However, just adding an event is not super helpful. So here’s an example of a base class that adds a bit more.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;

namespace MVVMBase
{
public class ViewModelBase : INotifyPropertyChanged
{
//The interface only includes this evennt
public event PropertyChangedEventHandler PropertyChanged;

    //Common implementations of SetProperty
    protected bool SetProperty&lt;T&gt;(ref T field, T value, [CallerMemberName]string name = null)
    {
        bool propertyChanged = false;

        //If we have a different value, do stuff
        if (!EqualityComparer&lt;T&gt;.Default.Equals(field, value))
        {
            field = value;
            OnPropertyChanged(name);
            propertyChanged = true;
        }

        return propertyChanged;
    }

    //The C#6 version of the common implementation
    protected void OnPropertyChanged([CallerMemberName]string name = null)
    {
       PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
    }
}

}

So what does it do:

  1. Implement INotifyPropertyChanged – yup, the event is there, job done.
  2. Creates a handy SetProperty method that does the following:
    1. Takes the property name, a reference to it’s backing field and the new value
    2. Checks if the new value is actually different
    3. If so it updates the backing field and invokes the property changed event
    4. Returns a value to indicate if the property actually changed
  3. Creates an OnPropertyChanged method (this is often also called RaisePropertyChanged) that can be used to force the PropertyChanged event to fire for a given property.

Now that I’ve got this, using it is pretty simple. First, make you view models inherit from this. Then write your properties this way:

private bool _messageReady;
public bool MessageReady
{
    get { return _messageReady; }
    set { SetProperty(ref _messageReady, value); }
}

Note that although SetProperty is generic, you don’t have to pass in a Type, and although it takes 3 propereties, and the third is the name of the property is being changed, you don’t have to as the default is set to the CallerMemberName attribute. Of course, you can do both and if you needed to do some thing where you set the property indirectly as part of some other method, you could then call SetProperty<bool>(ref _messageReady, true, “MessageReady”);

Some Properties are getter only and depend on the values of other properties and fields in the class. This is a place where that OnPropertyChanged method is useful.

private bool _messageReady; 
public bool MessageReady 
{ 
    get { return _messageReady; } 
    set 
    { 
        if (SetProperty(ref _messageReady, value))
        {
            OnPropertyChanged(() => BackgroundColor);
        }
    } 
}

public Color BackgroundColor
{
get { return MessageReady ? Colors.Green : Colors.White.
}

In this example, we have a property called BackgroundColor that is normally white, but becomes green when a message is ready. But as it’s just a getter, how does our UI know when it’s value changes? We call OnPropertyChanged for BackgroundColor when the MessageReady property is updated.

So that’s a brief tour of a view model base class.  If you look around, you will find others who may have more, or that have different implementations of these methods. For me, this is the basics of what you need – an implementation of INotifyPropertyChanged that you only need to make once, and that makes updating bound properties easy to do.

CodeSample: MVVMBase.zip

Update 3/10/2017: Added Code Sample, plus minor fixes. Update 9/22/2016: Note that in these code snippets, I’m inheriting ViewModelBaseClass which is where methods like SetProperty reside, and where INotifyPropertyChanged is implemented. If you are using a framework like MVVMLite or Prism, you will probably be using their base class. I’ll be…" data-origin=“213” data-position=“0”>The Command Pattern and MVVM

This is old news, in fact it’s been known about since 2007 and it’s by design. However, it came up at work today and it’s a surprise to me. Since it’s by design however, it’s both easy to fall into and easy to work around. Here’s the Microsoft support ticket.…" data-origin=“213” data-position=“1”>A memory leak may occur when you use data binding in Windows Presentation Foundation

Visual studio (and Blend) provide great tools to help you get an awesome design, and see how your screens / pages / controls are going to look.  Yet I work with several developers who never use the designer, at all, and go 100% XAML. On the other hand, I like to…" data-origin=“213” data-position=“2”>One design time strategy

<footer class="entry-footer">
	<div class="apostrophe-2-tags"><ul class="post-categories">
<li><a href="https://onewindowsdev.com/category/patterns/" rel="category tag">Patterns</a></li></ul><ul class="post-tags"><li><a href="https://onewindowsdev.com/tag/binding/" rel="tag">binding</a></li><li><a href="https://onewindowsdev.com/tag/mvvm/" rel="tag">MVVM</a></li><li><a href="https://onewindowsdev.com/tag/xaml/" rel="tag">XAML</a></li></ul></div>	<div class="entry-author author-avatar-show">
			<div class="author-avatar">
		<img alt="" src="https://0.gravatar.com/avatar/9d9a9ba0a74ed3a816855dd421ef7e66?s=125&amp;d=identicon&amp;r=G" class="avatar avatar-125 grav-hashed grav-hijack" height="125" width="125" id="grav-9d9a9ba0a74ed3a816855dd421ef7e66-0">		</div><!-- .author-avatar -->
	
	<div class="author-heading">
		<h2 class="author-title">Published by <span class="author-name">bluechrism</span></h2>
	</div><!-- .author-heading -->

	<p class="author-bio">
		I am a software developer with most professional experience in the Windows .Net realm and I'm currently a WPF developer with Starkey Labs.  However, I have wanted for some time to start the mobile developer journey properly and being an N900 owner, this was to be in the realm of QT.  Job hunting, moving to Minnesota and changing jobs put my plans on hold 6-12 months but things are starting to settle now, just as I'm getting sorted to start some things, Microsoft and Nokia merge.  This blog is about my novice mobile development experiences and hopefully will end up complete with links to download some apps on various platforms, but obviously by the name, Sybian, Maemo/Meego and Windows Mobile.

In other stuff, I am English, I support Everton FC, I have visited Glastonbury music festival 5 times and recommend it to anyone. I am married and my wife and i have a dog called Friday.


<nav class="navigation post-navigation" role="navigation" aria-label="Posts">
	<h2 class="screen-reader-text">Post navigation</h2>
	<div class="nav-links"><div class="nav-previous"><a href="https://onewindowsdev.com/2017/07/17/covariance-and-contravariance/" rel="prev"><span class="meta-nav">Previous</span> Covariance and Contravariance</a></div><div class="nav-next"><a href="https://onewindowsdev.com/2017/10/10/alternatives-for-groove/" rel="next"><span class="meta-nav">Next</span> Alternatives for Groove</a></div></div>
</nav>	</footer><!-- .entry-footer -->
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
提供的源码资源涵盖了安卓应用、小程序、Python应用和Java应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能够无缝运行。同时,源码中配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程中,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码中的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。
提供的源码资源涵盖了安卓应用、小程序、Python应用和Java应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能够无缝运行。同时,源码中配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程中,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码中的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。
提供的源码资源涵盖了安卓应用、小程序、Python应用和Java应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能够无缝运行。同时,源码中配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程中,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码中的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值