繁体   English   中英

如何将更改后的文本显示为原始文本几秒钟?

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

假设最初我在标签框中的文本为“ ABC”,当我单击按钮时,标签框中的文本将更改为“ DEF”并显示两秒钟,两秒钟后,它又回到“ ABC”。 与计时器或情节提要有关吗? 有什么建议么?

这是一种无需计时器的方法。 您可以捕获标签的当前文本,将其更改为新文本,然后使用后台工作程序“睡眠”两秒钟,然后将文本更改回:

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();
}

将原始值另存为临时字符串,然后启动计时器。 当计时器事件(滴答)触发时,使用它来检索旧值。

那应该足以让您入门:)

根据问题的标签,您正在使用C#和WPF应用程序。 我将使用一个Timer对象。

假设您的Label对象名为Label1 这将是放入应用程序的load()函数的函数体:

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

另外,如果您的WPF应用程序具有某种实现调用函数以处理Timer1Tick事件的方法,则将以下内容放入:

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

这样,它每两秒钟交替一次。

我可能是错的,但是我不经常将WPF应用程序与C#一起使用,而是将VB与Windows Forms应用程序一起使用。

一种非常简单的方法是在按钮处理程序中调用如下代码:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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