抱歉,我是 WPF 的新手:
当我单击一个按钮时,我希望在函数启动时看到标签中显示的一条消息,然后我希望在函数完成时看到另一条消息。
在这里的代码中,我只看到单击按钮时显示的最后一条消息值。有人可以向我解释为什么吗?
由于这不起作用,我将如何完成我真正想要的 - 在一段时间内看到一条消息(如“处理”),然后在函数完成时看到另一条消息(如“完成”)?
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
MessageLabel.Content = "I never see this";
System.Threading.Thread.Sleep(2000);
MessageLabel.Content = "I only see this";
}
}
谢谢布拉赫什玛!这是我想要的 BackgroundWorker 对象的代码。
public partial class MainWindow : Window
{
private BackgroundWorker backgroundWorker1 = new BackgroundWorker();
public MainWindow()
{
InitializeComponent();
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.WorkerSupportsCancellation = false;
backgroundWorker1.DoWork += worker_DoWork;
backgroundWorker1.RunWorkerCompleted += worker_RunWorkerCompleted;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
MessageLabel.Content = "I see this now";
if (backgroundWorker1.IsBusy != true)
{
backgroundWorker1.RunWorkerAsync();
}
}
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
System.Threading.Thread.Sleep(2000);
}
private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MessageLabel.Content = "and I see this too";
}
}