问题
I have custom control inherited from Textbox.
I want to make delay in calling textchanged event.
Observable.FromEventPattern<TextChangedEventHandler, TextChangedEventArgs>(
handler => this.TextChanged += handler,
handler => this.TextChanged -= handler
).Throttle(TimeSpan.FromMilliseconds(600))
.Where(e =>
{
var control= e.Sender as TextBox;
return control!= null && !string.IsNullOrEmpty(control.Text);
})
.Subscribe(x => Control_TextChanged(x.Sender, x.EventArgs));
Problem is it is giving error saying, cannot access Text property as current thread does not have access.
Can someone please advice?
Thanks, Vishal
回答1:
You can use ObserveOnDispatcher extension method and have something like:
Observable.FromEventPattern<TextChangedEventHandler, TextChangedEventArgs>(
ev => TextChanged += ev,
ev => TextChanged -= ev)
.Where(t => !string.IsNullOrEmpty(Text))
.Throttle(TimeSpan.FromMilliseconds(600))
.ObserveOnDispatcher()
.Subscribe(e => HandleTextChanged(e.EventArgs));
回答2:
You can observe on UI thread:
Observable.FromEventPattern<TextChangedEventHandler, TextChangedEventArgs>(
handler => this.TextChanged += handler,
handler => this.TextChanged -= handler)
.ObserveOn(DispatcherScheduler.Current)
.Throttle(TimeSpan.FromMilliseconds(600))
.Where(e =>
{
var control= e.Sender as TextBox;
return control!= null && !string.IsNullOrEmpty(control.Text);
})
.Subscribe(x => Control_TextChanged(x.Sender, x.EventArgs));
Notice the use of DispatcherScheduler.Current
it's in System.Reactive.Windows.Threading
namespace in Rx-WPF
NuGet package.
回答3:
You will have to use Control.Invoke()
to make changes to UI elements from any thread other than the main UI thread.
Where(e =>
{
var control= e.Sender as TextBox;
return control != null
&& !string.IsNullOrEmpty(Dispatcher.Invoke<string>(()=> control.Text));
})
来源:https://stackoverflow.com/questions/35169500/how-to-make-delay-in-calling-textchanged-event-of-textbox-in-wpf