【问题标题】:How do I update a Label from within a BackgroundWorker thread?如何从 BackgroundWorker 线程中更新标签?
【发布时间】:2015-08-04 13:17:18
【问题描述】:

当我使用 WinForms 时,我会在我的 bg_DoWork 方法中这样做:

status.Invoke(new Action(() => { status.Content = e.ToString(); }));
status.Invoke(new Action(() => { status.Refresh(); }));

但是,在我的 WPF 应用程序中,我收到一条错误消息,指出 Invoke 不存在 Label

任何帮助将不胜感激。

【问题讨论】:

    标签: c# wpf xaml backgroundworker


    【解决方案1】:

    使用BackgroundWorker 中已内置的功能。当您“报告进度”时,它会将您的数据发送到在 UI 线程上运行的 ProgressChanged 事件。无需拨打Invoke()

    private void bgWorker_DoWork(object sender, DoWorkEventArgs e)
    {
        bgWorker.ReportProgress(0, "Some message to display.");
    }
    
    private void bgWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        status.Content = e.UserState.ToString();
    }
    

    确保您设置bgWorker.WorkerReportsProgress = true 以启用报告进度。

    【讨论】:

    • 这个。因为您真的不想跨不同线程更新 UI 控件。
    【解决方案2】:

    如果您使用的是 WPF,我建议您查看 DataBinding。

    解决此问题的“WPF 方法”是将标签的 Content 属性绑定到模型的某些属性。这样,更新模型会自动更新标签,您不必担心自己编组线程。

    关于 WPF 和数据绑定的文章很多,这可能是一个很好的起点:http://www.wpf-tutorial.com/data-binding/hello-bound-world/

    【讨论】:

      【解决方案3】:

      这会对你有所帮助。

      同步执行:

      Application.Current.Dispatcher.Invoke(new Action(() => { status.Content = e.ToString(); }))
      

      异步执行:

      Application.Current.Dispatcher.BeginInvoke(new Action(() => { status.Content = e.ToString(); }))
      

      【讨论】:

        【解决方案4】:

        你需要使用

        Dispatcher.Invoke(new Action(() => { status.Content = e.ToString(); }))

        而不是status.Invoke(...)

        【讨论】:

          【解决方案5】:

          您真的应该考虑在 WPF 中使用“数据绑定”的强大功能。

          您应该更新视图模型中的对象并将其绑定到用户界面控件。

          请参阅 MVVM 灯。简单易用。不要在没有它的情况下编写 WPF。

          【讨论】:

          • 你不需要任何花哨的框架来使用 MVVM 设计模式。虽然它确实让一些事情更容易管理。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-05-14
          • 2016-01-02
          相关资源
          最近更新 更多