-3

How to make the text in the label change dynamically AFTER opening the window? (the window opens, text 1 is displayed, after a few seconds it changes to text2 ...)

public MainWindow()
{
    InitializeComponent();
    System.Threading.Thread.Sleep(5000);
    lblText.Content = "Sent for analysis";
    System.Threading.Thread.Sleep(5000);
    lblText.Content = "Analysis in progress";
    System.Threading.Thread.Sleep(5000);
    lblText.Content = "Analysis results";
}

At this moment, the window is displayed only when all operations are performed and only the last text is visible.

This is an example code. There is an API in my program and waiting for a response. The window is shown only after the whole code has been executed and how Api will respond (after 15sec).

I want it to work in the net framework 3.0.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
erbeen
  • 67
  • 6
  • Probably window events and timers would be the way to go. – Uwe Keim Apr 04 '19 at 09:04
  • You need the call to the API to be `async` then you need to apply the value of the lbl on the UI thread. Or you could have a View Model and do this proper way and not throwing code anywhere. – XAMlMAX Apr 04 '19 at 09:10
  • 1
    Also use databinding, and bind the label.Text to a string in VIewModel. Update it asynchronously. Do not update label directly. And Never use Thread.Sleep for wait, ALways use Task.Delay(ms) – Code Name Jack Apr 04 '19 at 09:27

1 Answers1

-2

Putting things in constructor will block window from loading.For a quick hack, Move things to OnContentRendered. Also make asynchronous calls and remove Thread.Sleep bool _shown;

protected override void OnContentRendered(EventArgs e)
{
    Task.Delay(5000);
    lblText.Content = "Sent for analysis";
    Task.Delay(5000);
    lblText.Content = "Analysis in progress";
    Task.Delay(5000);
    lblText.Content = "Analysis results";
}

Note: Even though this soultion would work, I don't suggest doing this. I would recommend spending some time on understanding WPF and then trying it the WPF way. With a proper code design(Use async-await and some MVVM with Zero codebehind) .

Code Name Jack
  • 2,856
  • 24
  • 40