Updating the user interface in WPF element event handlers

WPF has a problem with updating the user interface.

I have a code like this:

private void ButtonClick_EventHandler(object sender, RoutedEventArgs e) { Label.Visibility = Visibility.Visible; TextBox.Text = "Processing..."; LongTimeMethod(); //some long operation } 

The problem is that until the end of LongTimeMethod (the event handler ends) Label.Visibility and TextBox.Text will not be changed.

I solved it like this:

  private void ButtonClick_EventHandler(object sender, RoutedEventArgs e) { Label.Visibility = Visibility.Visible; TextBox.Text = "Processing..."; Dispatcher.BeginInvoke(new Action(LongTimeMethod), DispatcherPriority.Background); } 

Is there any other solution without using a dispatch call? Calling this.UpdateLayout () does not help.

+7
source share
2 answers

With Dispatcher.BeginInvoke you are still using the UI thread for LongTimeMethod() . If this is not required (i.e., it does some background processing), I would suggest using TPL to run in the background thread:

 private void ButtonClick_EventHandler(object sender, RoutedEventArgs e) { Label.Visibility = Visibility.Visible; TextBox.Text = "Processing..."; Task.Factory.StartNew(() => LongTimeMethod()) .ContinueWith(t => { Dispatcher.BeginInvoke((Action)delegate() { TextBox.Text = "Done!"; }); }); } 

With this method, the long method is processed in the background thread (so the user interface thread will be free to render and the application will not freeze), and you can do anything that changes the user interface (for example, updating text field text) in the Dispatcher user interface when background task completed

+4
source

Visibility and text are dependency properties that are updated by the dispatcher. Your decision is absolutely corrupt, but I suggest doing it asynchronously.

Alternatively, you can mimic Application.DoEvents in WPF ( see article ).

+1
source

All Articles