WPF で INotifyPropertyChanged の実装 サンプル コード

0 件のコメント

INotifyPropertyChanged インターフェイス を実装したサンプルコードを掲載します。 (…どちらかと言うと、自分の覚書。。)

サンプル コード

単純にインターフェイスを実装するだけなので、難しくはありません。 …が、PropertyChanged イベント を発生させるメソッド OnPropertyChanged を追加しています。 OnPropertyChanged の引数に CallerMemberName でプロパティ名を自動入力できるようにしているところがポイントです。

ViewModelBase.cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
namespace WpfApplication.ViewModels
{
    using System.ComponentModel;
    using System.Runtime.CompilerServices;
 
    /// <summary>
    /// ViewModel 基底クラス を表現します。
    /// </summary>
    public class ViewModelBase : INotifyPropertyChanged
    {
        /// <summary>
        /// プロパティ値が変更されたことをクライアントに通知します。
        /// </summary>
        public event PropertyChangedEventHandler PropertyChanged;
 
        /// <summary>
        /// PropertyChanged イベント を発生させます。
        /// </summary>
        /// <param name="propertyName">変更されたプロパティの名前</param>
        protected void OnPropertyChanged([CallerMemberName] string propertyName = "")
        {
            if (this.PropertyChanged != null)
            {
                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}

利用例

上記の基底クラスを利用した派生 ViewModel クラス の実装例を以下に載せます。 OnPropertyCnahged は デフォルトで呼び出し元メソッド名、プロパティ名を取得してくるので、特に引数を指定する必要がありません。

MainViewModel.cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
namespace WpfApplication.ViewModels
{
    using System.ComponentModel;
    using WpfApplication.Commands;
    using WpfApplication.Models;
 
    public class MainViewModel : ViewModelBase
    {
        private UserModel usermodel = null;
 
        public MainViewModel()
        {
            this.OpenMessageDialogCommand = new OpenMessageDialogCommand();
            this.UserModel = new UserModel();
        }
 
        public OpenMessageDialogCommand OpenMessageDialogCommand { get; set; }
 
        public UserModel UserModel
        {
            get
            {
                return this.usermodel;
            }
 
            set
            {
                if (this.usermodel == value)
                {
                    return;
                }
 
                this.usermodel = value;
                this.OnPropertyChanged();
            }
        }
    }
}

最後に… このブログに興味を持っていただけた方は、 ぜひ 「Facebookページ に いいね!」または 「Twitter の フォロー」 お願いします!!