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 -->
发布了1 篇原创文章 · 获赞 0 · 访问量 5724

猜你喜欢

转载自blog.csdn.net/RickyXiongStrive/article/details/104258471
今日推荐