RaspberryIO/Unosquare.Swan.Lite/Abstractions/ViewModelBase.cs
2019-12-04 17:10:06 +01:00

124 lines
5.0 KiB
C#

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
namespace Unosquare.Swan.Lite.Abstractions {
/// <summary>
/// A base class for implementing models that fire notifications when their properties change.
/// This class is ideal for implementing MVVM driven UIs.
/// </summary>
/// <seealso cref="INotifyPropertyChanged" />
public abstract class ViewModelBase : INotifyPropertyChanged {
private readonly ConcurrentDictionary<String, Boolean> QueuedNotifications = new ConcurrentDictionary<String, Boolean>();
private readonly Boolean UseDeferredNotifications;
/// <summary>
/// Initializes a new instance of the <see cref="ViewModelBase"/> class.
/// </summary>
/// <param name="useDeferredNotifications">Set to <c>true</c> to use deferred notifications in the background.</param>
protected ViewModelBase(Boolean useDeferredNotifications) => this.UseDeferredNotifications = useDeferredNotifications;
/// <summary>
/// Initializes a new instance of the <see cref="ViewModelBase"/> class.
/// </summary>
protected ViewModelBase()
: this(false) {
// placeholder
}
/// <summary>
/// Occurs when a property value changes.
/// </summary>
/// <returns></returns>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>Checks if a property already matches a desired value. Sets the property and
/// notifies listeners only when necessary.</summary>
/// <typeparam name="T">Type of the property.</typeparam>
/// <param name="storage">Reference to a property with both getter and setter.</param>
/// <param name="value">Desired value for the property.</param>
/// <param name="propertyName">Name of the property used to notify listeners. This
/// value is optional and can be provided automatically when invoked from compilers that
/// support CallerMemberName.</param>
/// <param name="notifyAlso">An rray of property names to notify in addition to notifying the changes on the current property name.</param>
/// <returns>True if the value was changed, false if the existing value matched the
/// desired value.</returns>
protected Boolean SetProperty<T>(ref T storage, T value, [CallerMemberName] String propertyName = "", String[] notifyAlso = null) {
if(EqualityComparer<T>.Default.Equals(storage, value)) {
return false;
}
storage = value;
this.NotifyPropertyChanged(propertyName, notifyAlso);
return true;
}
/// <summary>
/// Notifies one or more properties changed.
/// </summary>
/// <param name="propertyNames">The property names.</param>
protected void NotifyPropertyChanged(params String[] propertyNames) => this.NotifyPropertyChanged(null, propertyNames);
/// <summary>
/// Notifies one or more properties changed.
/// </summary>
/// <param name="mainProperty">The main property.</param>
/// <param name="auxiliaryProperties">The auxiliary properties.</param>
private void NotifyPropertyChanged(String mainProperty, String[] auxiliaryProperties) {
// Queue property notification
if(String.IsNullOrWhiteSpace(mainProperty) == false) {
this.QueuedNotifications[mainProperty] = true;
}
// Set the state for notification properties
if(auxiliaryProperties != null) {
foreach(String property in auxiliaryProperties) {
if(String.IsNullOrWhiteSpace(property) == false) {
this.QueuedNotifications[property] = true;
}
}
}
// Depending on operation mode, either fire the notifications in the background
// or fire them immediately
if(this.UseDeferredNotifications) {
_ = Task.Run(() => this.NotifyQueuedProperties());
} else {
this.NotifyQueuedProperties();
}
}
/// <summary>
/// Notifies the queued properties and resets the property name to a non-queued stated.
/// </summary>
private void NotifyQueuedProperties() {
// get a snapshot of property names.
String[] propertyNames = this.QueuedNotifications.Keys.ToArray();
// Iterate through the properties
foreach(String property in propertyNames) {
// don't notify if we don't have a change
if(!this.QueuedNotifications[property]) {
continue;
}
// notify and reset queued state to false
try {
this.OnPropertyChanged(property);
} finally { this.QueuedNotifications[property] = false; }
}
}
/// <summary>
/// Called when a property changes its backing value.
/// </summary>
/// <param name="propertyName">Name of the property.</param>
private void OnPropertyChanged(String propertyName) =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName ?? String.Empty));
}
}