Created
June 27, 2017 14:32
-
-
Save nnm-t/262ec74eaf27ca524eaaa15486bed72b to your computer and use it in GitHub Desktop.
INotifyPropertyChangedを使用してUnityでオレオレMVVM
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; | |
using System.Linq.Expressions; | |
using System.ComponentModel; | |
using UnityEngine; | |
public abstract class BindableMonoBehaviour : MonoBehaviour, INotifyPropertyChanged | |
{ | |
//プロパティの値の変更を通知するイベントハンドラ | |
public event PropertyChangedEventHandler PropertyChanged; | |
protected bool SetProperty<T>(ref T storage, T value, Expression<Func<T>> propertyExpression) | |
{ | |
return SetProperty(ref storage, value, null, propertyExpression); | |
} | |
protected bool SetProperty<T>(ref T storage, T value, Action onChanged, Expression<Func<T>> propertyExpression) | |
{ | |
// バッキングフィールドに値を代入して変更を通知する | |
if (Equals(storage, value)) | |
{ | |
return false; | |
} | |
storage = value; | |
if (onChanged != null) | |
{ | |
onChanged(); | |
} | |
if (propertyExpression == null) | |
{ | |
throw new ArgumentNullException("propertyExpression"); | |
} | |
RaisePropertyChanged(propertyExpression); | |
return true; | |
} | |
protected void RaisePropertyChanged<T>(Expression<Func<T>> propertyExpression) | |
{ | |
RaisePropertyChanged((MemberExpression)e.Body.Member.Name); | |
} | |
protected void RaisePropertyChanged(string propertyName) | |
{ | |
//値の変更を通知 | |
if (PropertyChanged != null) | |
{ | |
PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
メソッド名とかはPrismのパクりなので同じ感覚で使えます
Unity 5.6の時点ではCaller Infoが使えないのでSetPropertyメソッドでいちいちラムダ書かないといけないのが面倒