这是我想要实现的目标(在.Net 4 WPF客户端中):
从我所看到的反应性扩展非常适合这种情况,但我遇到了麻烦,特别是第4步。
其次我使用的是mvvm,所以如何在视图中订阅TextBox.TextChanged时将此逻辑放在视图模型中。
答案 0 :(得分:4)
一些运营商在这里非常方便(值得注意的是,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)。然后结果块可以绑定到Output。