ここでは、いくつかの演算子が非常に便利です (特に、Throttle
2 とSwitch
4 の場合)。ビューモデルは次のようになります。
Class ViewModel
Implements INotifyPropertyChanged
Implements IDisposable 'to clean up subscription
Public Sub New()
_subscription = Observable.FromEventPattern(Of PropertyChangedEventHandler, PropertyChangedEventArgs)(
Sub(h) AddHandler Me.PropertyChanged, h,
Sub(h) RemoveHandler Me.PropertyChanged, h) _
.Where(Function(ep) String.Equals(ep.EventArgs.PropertyName, "Input", StringComparison.Ordinal)) _
.Throttle(TimeSpan.FromSeconds(0.5)) _
.Select(Function(ep) Validate(Me.Input)) _
.Switch() _
.ObserveOnDispatcher() _
.Subscribe(Sub(v) Me.Output = v)
End Sub
Private ReadOnly _subscription As IDisposable
'put in actual code to notify on change
Public Property Input As String
Public Property Output As ValidationResult
Private Function Validate(toValidate As String) As IObservable(Of ValidationResult)
'start validation
End Function
Public Event PropertyChanged(sender As Object, e As PropertyChangedEventArgs) Implements INotifyPropertyChanged.PropertyChanged
End Class
ビューから、テキスト ボックスを Input にバインドし、バインド モードを PropertyChanged (既定の LostFocus ではなく) に設定します。その後、結果ブロックを出力にバインドできます。