LoginSignup
2
2

More than 5 years have passed since last update.

[C#][MVVM Light Toolkit] ViewModelBaseを継承したBindableBase実装を行なう

Posted at

MVVM Light Toolkit のViewModelBaseの書き方がそのままだと冗長なので、よくあるBindableBaseで使えるようにする。

MVVM Light Toolkitについては以下

BindableBaseについては以下などを参照

実装例

とはいっても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);
        }
    }

参考

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2