[英]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應用程序具有某種實現調用函數以處理Timer1
的Tick
事件的方法,則將以下內容放入:
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.