Text of a TextBox in C# (xaml) doesn't change at runtime

1.3k Views Asked by At

I've done a GUI in VisualStudio and used a TextBox to show to user what's happening.

I use myTextBox.AppendText to show information like

myTextBox.AppendText("\n" + DateTime.Now.ToLocalTime() + ": " + serviceName + " waiting for stopping");
service.Stop();
service.WaitForStatus(ServiceControllerStatus.Stopped);
service.Close();
myTextBox.AppendText("\n" + DateTime.Now.ToLocalTime() + ": " + serviceName + " has been stopped correcly");

and so on. The TextBox, anyway, is filled with the Text only when all jobs are completed. So, when all my code has finished to be run, the TextBox is filled with all the strings. So, I would like to print the string at the time I call AppendText. Are I missing anything? Maybe is anything thread-freezing like in java?

Thank you in adavnce.

3

There are 3 best solutions below

1
Dean Chalk On

Your problem is that your service calls are (apparently) running on the UI thread, so nothing will show until they have stopped blocking the thread.

You need to put your service calls on a background thread, then change your textbox text by marshalling the change up to the UI thread via the dispatcher

2
Jan Paolo Go On

So, when all my code has finished to be run, the TextBox is filled with all the strings. So, I would like to print the string at the time I call AppendText

If I understood that statement correctly, you want to replace the text in the TextBox each time instead of adding some text into it. If that's the case, you should use the TextBox.Text property instead of AppendText

TextBox.Text

Setting this property replaces the contents of the text box with the specified string.

AppendText

use this method to add text to the existing text

0
paparazzo On

this is what i use

public static class ExtensionMethods
{
   private static Action EmptyDelegate = delegate() { };

   public static void Refresh(this UIElement uiElement)
   {
      uiElement.Dispatcher.Invoke(DispatcherPriority.Render, EmptyDelegate);
   }
}
private void LoopingMethod()
{
   for (int i = 0; i < 10; i++)
   {
      label1.Content = i.ToString();
      label1.Refresh();
      Thread.Sleep(500);
   }
}

typically the UI does not refresh until the code behind completes
you need to force a refresh