LoginSignup
0
1

More than 3 years have passed since last update.

【C#】プロパティ名を文字列として取得

Posted at

久しぶりにWPFを使っていてViewModelのPropertyChangedを発行する際の
プロパティ名を固定値ではなく動的に取得するようにしておきたかったのでメモ。
#使わなくなるとすぐ忘れてしまったので…

サンプル
public class HogeModel : INotifyPropertyChanged
{
    int _param1;

    public int Param1
    {
        get { return _param1; }
        set { _param1 = value; OnPropertyChanged(); }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged([CallerMemberName] string propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

[CallerMemberName]で呼び出し元のメソッド名を取得出来るので
単純に自身の変更通知を行う場合は引数を指定しなくても
勝手に通知してくれます。
別プロパティの変更通知を行う場合や
通常のメソッド内で通知する場合は諦めてnameof演算子で取得するしかありませんが…。

0
1
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
0
1