Skip to content

Instantly share code, notes, and snippets.

@nnm-t
Created June 27, 2017 14:32
Show Gist options
  • Select an option

  • Save nnm-t/262ec74eaf27ca524eaaa15486bed72b to your computer and use it in GitHub Desktop.

Select an option

Save nnm-t/262ec74eaf27ca524eaaa15486bed72b to your computer and use it in GitHub Desktop.
INotifyPropertyChangedを使用してUnityでオレオレMVVM
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));
}
}
}
@nnm-t

nnm-t commented Jun 27, 2017

Copy link
Copy Markdown
Author

メソッド名とかはPrismのパクりなので同じ感覚で使えます
Unity 5.6の時点ではCaller Infoが使えないのでSetPropertyメソッドでいちいちラムダ書かないといけないのが面倒

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment