nprogram’s blog

気ままに、プログラミングのトピックについて書いていきます

INotifyPropertyChangedを使った簡単なWPFサンプル例 [C#][WPF]

サンプルコードについて

INotifyPropertyChangedを使って、プロパティ値が変更されたことをViewに通知するのみのサンプルコードです。
簡単化するため、ViewとModelしかありません。

BindableBaseクラスは、INotifyPropertyChangedインタフェースを継承しています。 このあたりの説明は、以下のサイトに記載されています。 blog.okazuki.jp

プログラムでは、MainWindowクラスのコンストラクタで、Personクラスのインスタンスをデータコンテキストに設定します。 そして、PersonクラスのインスタンスのNameプロパティを変更して、Viewに反映させています。

  • プロジェクト構成 f:id:nprogram:20180104150527p:plain

  • サンプル表示例 f:id:nprogram:20180104150605p:plain

[BindableBase.cs]

using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace WpfApp1
{
    public class BindableBase : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged([CallerMemberName]string propertyName = null) =>
            this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));

        protected virtual bool SetProperty<T>(ref T field, T value, [CallerMemberName]string propertyName = null)
        {
            if (EqualityComparer<T>.Default.Equals(field, value)) { return false; }
            field = value;
            this.OnPropertyChanged(propertyName);
            return true;
        }
    }
}

[Person.cs]

namespace WpfApp1
{
    public class Person : BindableBase
    {
        private string name;

        public string Name
        {
            get { return this.name; }
            set { this.SetProperty(ref this.name, value); }
        }
    }
}

[MainWindow.xaml]

<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp1"
        mc:Ignorable="d"
        Title="MainWindow" Height="167.828" Width="443.238">
    <TextBlock Text="{Binding Name}"/>
</Window>

[MainWindow.xaml.cs]

using System.Windows;

namespace WpfApp1
{
    /// <summary>
    /// MainWindow.xaml の相互作用ロジック
    /// </summary>
    public partial class MainWindow : Window
    {

        public MainWindow()
        {
            InitializeComponent();

            var person = new Person();

            // DataContextにモデルであるPersonクラスをバインド
            this.DataContext = person; 

            // PersonクラスのNameプロパティの値を"Hello"に書き換える
            person.Name = "Hello";      
        }
    }
}