简体   繁体   中英

How to display changed text for few seconds from its original text?

Let say initially my text in a label box is "ABC", when I clicked a button, the text in the label box will changed to "DEF" and display for two seconds, after two seconds it backs to "ABC" again. Is it something to do with timer or storyboarding? Any suggestions?

Here's one way to do it without a timer. You can capture the current text of the label, change it to the new text, and then use a background worker to "sleep" for two seconds and change the text back:

private void button1_Click(object sender, EventArgs e)
{
    // To keep the user from repeatedly pressing the button, let's disable it
    button1.Enabled = false;

    // Capture the current text ("ABC" in your example)
    string originalText = label1.Text;

    // Create a background worker to sleep for 2 seconds...
    var backgroundWorker = new BackgroundWorker();
    backgroundWorker.DoWork += (s, ea) => Thread.Sleep(TimeSpan.FromSeconds(2));

    // ...and then set the text back to the original when the sleep is done
    // (also, re-enable the button)
    backgroundWorker.RunWorkerCompleted += (s, ea) =>
    {
        label1.Text = originalText;
        button1.Enabled = true;
    };

    // Set the new text ("CDE" in your example)
    label1.Text = "CDE";

    // Start the background worker
    backgroundWorker.RunWorkerAsync();
}

Save the original Value as a temporary string somewhere, then start a timer. When the timer event (tick) fires, use that to retrieve the old value.

That should be more then enough to get you started :)

Basing of the tags of your question, you're using C# and a WPF application. I'd go with a Timer object.

Say your Label object is named Label1 . This would be a function body to put in your app's load() function:

Label1.text = "ABC";
Timer1.duration = 2000;
Timer1.enabled = TRUE;

In addition, if your WPF application has some sort of way to implement a way to call a function to handle Timer1 's Tick event, put something like this in:

if (Label1.text == "ABC") {
Label1.text = "DEF";
} else {
Label1.text = "ABC";
}

That way, it alternates every two seconds.

I may be wrong, but I don't often use WPF applications with C#, I use VB with a Windows Forms Application.

A very simple way to do this would be calling something like this inside your button handler:

        private async void changeText() 
    {
        label1.Text = "DEF";
        await Task.Delay(2000);
        label1.Text = "ABC";
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM