BindableBaseは、INotifyPropertyChangedを実装する際のヘルパークラスです。
MVVMにおいて、View - ViewModel間の状態変化を通知するためにはINotifyPropertyChangedを実装しなければいけませんが、.NET標準機能のみで実装すると非常に手間です。
PrismのBindableBaseは、ViewModelを作成するための基底クラスを提供します。
PrismBindableBaseでは、データバインディングするプロパティにはSetProperty()を実行するように実装します。
protected virtual bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null);
SetProperty()でプロパティの変更通知(PropertyChanged)やプロパティ名の暗黙的取得などバインディングに必要な処理を内包しています。
using Prism.Mvvm; namespace WpfPrismMvvm { public class MainWindowViewModel : BindableBase { private string _bindtext; public string BindText { get { return _bindtext; } set { SetProperty(ref _bindtext, value); } } } }
<Window x:Class="WpfPrismMvvm.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="320" Width="480"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="2*"/> <RowDefinition Height="1*"/> </Grid.RowDefinitions> <Label Content="{Binding BindText}" Margin="10" Background="LightGray" Grid.Row="0"/> <TextBox Text="{Binding BindText, UpdateSourceTrigger=PropertyChanged}" x:Name="EditBox" Margin="10" Background="White" TextWrapping="Wrap" Grid.Row="1" AcceptsTab="True" AcceptsReturn="True"/> </Grid> </Window>
using System.Windows; namespace WpfPrismMvvm { /// <summary> /// MainWindow.xaml の相互作用ロジック /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); MainWindowViewModel vm = new MainWindowViewModel(); this.DataContext = vm; } } }