Skip to content

Instantly share code, notes, and snippets.

@jahands
Created May 28, 2015 19:44
Show Gist options
  • Save jahands/9e4e790d1d28c6bbc9b9 to your computer and use it in GitHub Desktop.
Save jahands/9e4e790d1d28c6bbc9b9 to your computer and use it in GitHub Desktop.
MVVM Light additional ObservableObject.Set() methods to allow arbitrary backing fields & easier object wrapping.
// This would allow using properties as the backing fields.
// Useful when making models which wrap an object and use an
// instance of that object for the backing field, as
// shown in the example below.
// Usage:
public class PersonViewModel : EasyObservableObject
{
private Person p = new Person();
public string FirstName
{
get { return p.FirstName; }
set { Set("FirstName", x => p.FirstName = x, p.FirstName, value); }
}
public string LastName
{
get { return p.LastName; }
set { Set(x => p.LastName = x, p.LastName, value); }
}
}
// Implementationn:
/// <summary>
/// Assigns a new value to the property. Then, raises the
/// PropertyChanged event if needed.
/// </summary>
/// <typeparam name="T">The type of property that
/// changed.</typeparam>
/// <param name="setField">Action to execute to set the
/// field's value.</param>
/// <param name="oldValue">The current value of the field.</param>
/// <param name="newValue">The property's value after the change
/// occured.</param>
/// <param name="propertyName">The name of the property that changed.</param>
/// <returns>True if the PropertyChanged event has been raised,
/// false otherwise. The event is not raised if the old
/// value is equal to the new value.</returns>
protected bool Set<T>(
Action<T> setField,
T oldValue,
T newValue,
[CallerMemberName]string propertyName = null)
{
return Set(propertyName, setField, oldValue, newValue);
}
/// <summary>
/// Assigns a new value to the property. Then, raises the
/// PropertyChanged event if needed.
/// </summary>
/// <typeparam name="T">The type of property that
/// changed.</typeparam>
/// <param name="propertyName">(Optional) The name of the property
/// that changed.</param>
/// <param name="setField">Action to execute to set the
/// field's value.</param>
/// <param name="oldValue">The current value of the field.</param>
/// <param name="newValue">The property's value after the change
/// occured.</param>
/// <returns>True if the PropertyChanged event has been raised,
/// false otherwise. The event is not raised if the old
/// value is equal to the new value.</returns>
protected bool Set<T>(
string propertyName,
Action<T> setField,
T oldValue,
T newValue)
{
if (EqualityComparer<T>.Default.Equals(oldValue, newValue))
{
return false;
}
setField(newValue);
RaisePropertyChanged(propertyName);
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment