2015-05-22 21 views
1

當我使用的WinForms,我會在我的bg_DoWork方法做到了這一點:如何從BackgroundWorker線程內更新標籤?

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

但是在我的WPF應用程序,我得到一個錯誤,指出Invoke不爲Label存在。

任何幫助,將不勝感激。

回答

1

這會幫助你。

同步執行:

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

異步執行:

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

您需要使用的

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

代替status.Invoke(...)

7

使用已經內置到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以啓用報告進度。

+1

這個。因爲你不想在不同的線程上更新UI控件。 –

2

如果你使用WPF,我會建議尋找到數據綁定。

要解決這個問題的「WPF方法」是將標籤的Content屬性綁定到模型的某些屬性。這樣,更新模型會自動更新標籤,您不必擔心自己編組線程。

上有WPF和數據綁定的文章很多,這很可能是個好位置,開始爲所有:http://www.wpf-tutorial.com/data-binding/hello-bound-world/

1

你真的應該考慮使用的「數據綁定」在WPF的權力。

您應該更新視圖模型中的對象並將其綁定到用戶界面控件。

請參閱MVVM Light。簡單易用。沒有它,不要編碼WPF。

+2

您不需要*任何花哨的框架來使用MVVM設計模式。儘管它確實讓一些事情更容易管理。 –

+0

MVVM Light非常棒。 – Contango