INotifyPropertyChanged インターフェイスは、プロパティ値が変更されたことをクライアント (通常はバインド元クライアント) に通知するためのインターフェースです。
INotifyPropertyChanged インターフェイスは、双方向通信(データバインディング)を実現するための主要な要素といえます。
INotifyPropertyChangedは、eventが1つ定義されているだけのシンプルな構成となっています。
namespace System.ComponentModel { public interface INotifyPropertyChanged { event PropertyChangedEventHandler PropertyChanged; } }
INotifyPropertyChanged を継承したViewModel 基底クラス を用意し、ViewModelはこの基底クラスを継承する手法が一般的です。
namespace WpfDevelop { 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)); } } } }
ViewModelBaseを継承し、setプロパティにおいて「OnPropertyChanged()」を呼び出すように定義します。
namespace WpfDevelop { public class MainWindowViewModel : ViewModelBase { private string _bindText = string.Empty; public string BindText { get { return this._bindText; } set { this._bindText = value; OnPropertyChanged(nameof(BindText)); return; } } } }
.xaml
<Window x:Class="WpfDevelop.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" mc:Ignorable="d" Title="MainWindow" Height="480" Width="640"> <Grid Background="DarkSlateGray"> <Grid.RowDefinitions> <RowDefinition Height="2*"/> <RowDefinition Height="1*"/> </Grid.RowDefinitions> <Label Margin="10" Background="LightGray" Grid.Row="0" Content="{Binding BindText, Mode=OneWay}"/> <TextBox x:Name="EditBox" Margin="10" Background="White" Grid.Row="1" AcceptsTab="True" AcceptsReturn="True" Text="{Binding BindText, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/> </Grid> </Window>
xaml.cs
namespace WpfDevelop { using System.Windows; /// <summary> /// MainWindow.xaml の相互作用ロジック /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); MainWindowViewModel vm = new MainWindowViewModel(); this.DataContext = vm; } } }