对不起,对于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";
}
}
谢谢你Blachshma!下面是使用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";
}
}
答案 0 :(得分:2)
您没有看到更改的原因是因为这一切都在UI线程上运行,在第二次更新标签之后,在之后没有机会刷新屏幕。
您应该使用 BackgroundWorker 来运行代码的“重”部分(例如标签的Sleep +更新)
代码的快速示例:
private void Button_Click(object sender, RoutedEventArgs e)
{
MessageLabel.Content = "I never see this";
BackgroundWorker bw = new BackgroundWorker();
bw.DoWork += (s,a) =>
{
Thread.Sleep(2000);
};
bw.RunWorkerCompleted += (s, a) =>
{
MessageLabel.Content = "I saw it now";
};
bw.RunWorkerAsync(); // Start BackgroundWorker