MVVM Light Toolkit のViewModelBaseの書き方がそのままだと冗長なので、よくあるBindableBaseで使えるようにする。
MVVM Light Toolkitについては以下
BindableBaseについては以下などを参照
- WPFでもBindableBaseを使ってINotifyPropertyChangedを実装する - SourceChord
- [MVVM] 便利で間違えのないプロパティ変更通知を行うBindableBaseの実装 – Tech.D-ITlab | Denso IT Laboratory researcher's blog sites
実装例
とはいってもViewModelBaseを継承してBindableBaseの実装をしているだけですが・・・。
ViewModelBaseの拡張メソッドでもいいですが、いちいち using
つけたり SetProperty
の全部に this.
をつけないといけなかったりと、主にIDE的な都合で面倒だったので特に理由がなければ継承のほうが楽そうです。
BindableBase.cs
public class BindableBase : ViewModelBase
{
protected BindableBase()
{
}
protected BindableBase(IMessenger messenger) : base(messenger)
{
}
protected bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
{
if (Equals(storage, value)) return false;
storage = value;
RaisePropertyChanged(propertyName);
return true;
}
}
使い方もよくあるものと変わりません。違う点は MVVM Light Toolkit 向けの Messanger の実装がそのままというところだけです。
使用例
public class BindableBaseImplSample : BindableBase
{
public BindableBaseImplSample(Model model)
: base(Messenger.Default)
{
}
private string _name;
public string Name
{
get => _name;
set => SetProperty(ref _name, value);
}
}