Skip to content

Instantly share code, notes, and snippets.

@rzhw
Created October 13, 2013 00:57
Show Gist options
  • Save rzhw/6956761 to your computer and use it in GitHub Desktop.
Save rzhw/6956761 to your computer and use it in GitHub Desktop.
using Cirrious.MvvmCross.ViewModels;
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace Blah
{
public static class MvvmCrossRaiseAndSetIfChanged
{
/// <summary>
/// RaiseAndSetIfChanged fully implements a Setter for a read-write
/// property on a ReactiveObject, using CallerMemberName to raise the notification
/// and the ref to the backing field to set the property.
///
/// This method is copied from ReactiveUI/ReactiveObject.cs as it only works on ReactiveObject
/// </summary>
/// <typeparam name="TObj">The type of the This.</typeparam>
/// <typeparam name="TRet">The type of the return value.</typeparam>
/// <param name="This">The <see cref="ReactiveObject"/> raising the notification.</param>
/// <param name="backingField">A Reference to the backing field for this
/// property.</param>
/// <param name="newValue">The new value.</param>
/// <param name="propertyName">The name of the property, usually
/// automatically provided through the CallerMemberName attribute.</param>
/// <returns>The newly set value, normally discarded.</returns>
public static TRet RaiseAndSetIfChanged<TObj, TRet>(
this TObj This,
ref TRet backingField,
TRet newValue,
[CallerMemberName] string propertyName = null)
where TObj : MvxViewModel
{
Contract.Requires(This != null);
Contract.Requires(propertyName != null);
if (EqualityComparer<TRet>.Default.Equals(backingField, newValue))
{
return newValue;
}
backingField = newValue;
This.RaisePropertyChanged(propertyName);
return newValue;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment