Binding(更新)の実装
C#の処理結果をBindしているコントロールに反映させる時は INotifyPropertyChanged インターフェースを利用する
- INotifyPropertyChanged の実装例
class ViewModel : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private void RaisePropertyChanged( string propertyName ) { this.PropertyChanged?.Invoke( this, new PropertyChangedEventArgs( propertyName ) ); } }
使用例
CheckBoxのCheck/Uncheck切り替えに連動して文字列を更新する
- Xaml
<CheckBox IsChecked="{Binding CheckBox1}" Content="{Binding Label1}"/>
- ViewModel
private bool _CheckBox1 = false; public bool Checkbox1 { get { return this._CheckBox1; } set { this._CheckBox1 = value; this.RaisePropertyChanged( string.Empty ); } } public string Label1 { get { if( this.CheckBox1 ) { return "Checked!"; } return "Unchecked!"; } }
- RaisePropertyChangedの引数にプロパティ名を入れた場合、そのプロパティにBindしたコントロールだけを更新できる
- 例のようにstring.Empty を入れた時は、全てのBindが更新される