Last active
December 19, 2024 16:54
-
-
Save DanRigby/98fd60dd32df82a678cd to your computer and use it in GitHub Desktop.
BindableBase class for implementing INotifyPropertyChanged using C# 6 features while targeting .NET 2.0 to .NET 4.0. Make sure to use the nameof() operator for passing the propertyName parameter.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.ComponentModel; | |
/// <summary> | |
/// Implementation of <see cref="INotifyPropertyChanged" /> to simplify models. | |
/// </summary> | |
public abstract class BindableBase : INotifyPropertyChanged | |
{ | |
/// <summary> | |
/// Multicast event for property change notifications. | |
/// </summary> | |
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.</param> | |
/// <returns> | |
/// True if the value was changed, false if the existing value matched the | |
/// desired value. | |
/// </returns> | |
protected bool SetProperty<T>(ref T storage, T value, string propertyName) | |
{ | |
if (Equals(storage, value)) | |
{ | |
return false; | |
} | |
storage = value; | |
this.OnPropertyChanged(propertyName); | |
return true; | |
} | |
/// <summary> | |
/// Notifies listeners that a property value has changed. | |
/// </summary> | |
/// <param name="propertyName">Name of the property used to notify listeners./>. | |
/// </param> | |
protected void OnPropertyChanged(string propertyName) | |
{ | |
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment