在這裏有一些運營商相當方便(特別是,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
從視圖,綁定的文本框中輸入和設置綁定模式的PropertyChanged(而不是默認的引發LostFocus)。結果塊可以綁定到輸出。
如果您是Rx的新手,這可能會過於陡峭的學習曲線,但是當您使用Rx和WPF時,[ReactiveUI](http://www.reactiveui.net/)非常棒。所以這可能值得一試。 – Wilka