1

抱歉,我是 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";
    }
}
4

1 回答 1

2

您看不到更改的原因是因为这一切都在 UI 线程上运行,直到第二次更新标签之后才有机会刷新屏幕。
您应该使用BackgroundWorker来运行代码的“繁重”部分(例如,标签的睡眠 + 更新)

您的代码的快速示例:

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
于 2013-03-25T23:53:28.930 回答