Skip to content

Instantly share code, notes, and snippets.

@nord-
Created August 14, 2019 11:27
Show Gist options
  • Save nord-/10f0b9460d5d598628a3c8694011c659 to your computer and use it in GitHub Desktop.
Save nord-/10f0b9460d5d598628a3c8694011c659 to your computer and use it in GitHub Desktop.
Observable property base class for Xamarin Forms (applicable to WPF as well, just remove the ContentPageBase class)
using System.ComponentModel;
using System.Runtime.CompilerServices;
using Xamarin.Forms;
namespace ChargeNode
{
[DefaultProperty("Value")]
public class ObservableProperty<T> : ObservablePropertyBase
{
private T _value;
public ObservableProperty() { }
public ObservableProperty(T value)
{
Value = value;
}
public T Value
{
get => _value;
set { _value = value; OnPropertyChanged(); }
}
public static bool operator ==(ObservableProperty<T> self, T other)
{
return self._value.Equals(other);
}
public static bool operator !=(ObservableProperty<T> self, T other)
{
return !self._value.Equals(other);
}
}
public class ContentPageBase<T> : ContentPage where T : ObservablePropertyBase
{
protected T PageViewModel
{
get => BindingContext as T;
set => BindingContext = value;
}
}
public abstract class ObservablePropertyBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string propertyName = null) =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment