[英]How to make C# button click only one time and make a textbox show two result?
I write below simple code. 我写下面的简单代码。 I want to make this happen: 1. Click button.
我想做到这一点:1.单击按钮。 2. Show the first string.
2.显示第一个字符串。 3. Wait for 3 seconds.
3.等待3秒钟。 4. Show the second string.
4.显示第二个字符串。 But with this code, i can only see the second string after i click the button and wait for 3 seconds.
但是使用此代码,我仅在单击按钮并等待3秒钟后才能看到第二个字符串。 i can't see the first string.
我看不到第一个字符串。 is there any way to make this happen?
有什么办法可以做到这一点?
namespace clicktest
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void button_Click(object sender, RoutedEventArgs e)
{
this.textBox.Text = "Show 1st time";
Thread.Sleep(3000);
this.textBox.Text = "Show 2nd time";
}
}
}
Blocking a thread, such as when using Thread.Sleep
, in WPF prevents the GUI from refreshing. 阻塞线程(例如在WPF中使用
Thread.Sleep
时)会阻止GUI刷新。
Instead you can use await Task.Delay
which won't block the thread: 相反,您可以使用
await Task.Delay
,它不会阻塞线程:
private async void button_Click(object sender, RoutedEventArgs e)
{
this.textBox.Text = "Show 1st time";
await Task.Delay(3000);
this.textBox.Text = "Show 2nd time";
}
As @Alexander Higgins said, you can use await Task.Delay , but you have to add the async type to your method, like this: 正如@Alexander Higgins所说的,您可以使用await Task.Delay ,但是您必须将异步类型添加到您的方法中,如下所示:
private async void button_Click(object sender, RoutedEventArgs e)
{
this.textBox.Text = "Show 1st time";
await Task.Delay(3000);
this.textBox.Text = "Show 2nd time";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.