我的BackgroundWorker
放在UserControl
中有問題。 我的WPF應用程序在左側導航,每個條目加載自己的UserControl
,用戶可以在其中生成PDF文件。BackgroundWorker:在完成的事件中啓用/禁用按鈕在用戶控件之間切換後不工作
由於PDF的創建需要一些時間,我已經實現了BackgroundWorker
這個工作,另外我禁用了一些按鈕並顯示一個進度條。 在RunWorkerCompleted
事件中,我重置按鈕的狀態並隱藏進度條。
儘管存在一種情況,但所有這些工作都很好: 在創建PDF時,用戶可以在UserControl之間切換,並且如果他返回到開始作業的控件,控件應該顯示進度條並按鈕被禁用。 爲了達到這個目的,我在UserControl
上加了一個變量(isProcessing)。
一個控制的構造我有這樣的:
// Check if a current process is running, if so: handle button/progressbar visibility
if (_isProcessing)
{
_stkProgressBar.Visibility = Visibility.Visible;
progressBar1.IsIndeterminate = true;
// Disabling the buttons here is just working with a hack in
// the "Button_IsEnabledChanged" event.
btnDaten.IsEnabled = false;
btnBericht.IsEnabled = false;
this.Cursor = Cursors.Wait;
}
else
{
_stkProgressBar.Visibility = Visibility.Hidden;
}
啓用/禁用有剛剛工作,因爲這個骯髒的黑客的按鈕:
private void btnDaten_IsEnabledChanged(object sender, DependencyPropertyChangedEventArgs e)
{
//HACK: We want to disable the report buttons if a report execution is running.
// Disabling the buttons in the Load Event of the control isn't working
if (_isProcessing && (bool)e.NewValue)
{
btnDaten.IsEnabled = false;
btnBericht.IsEnabled = false;
}
}
現在,如果作業正在運行,並用戶在控件之間切換,處理控制的狀態很好。但是,如果作業結束並且PDF已準備就緒,則無法啓用按鈕,並且進度條也保持可見。該代碼被放置在RunWorkerCompleted
事件:
void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// This is not working if the user switches between the controls
_isProcessing = false;
this.Cursor = Cursors.Arrow;
_stkProgressBar.Visibility = Visibility.Hidden;
btnDaten.IsEnabled = true;
btnBericht.IsEnabled = true;
}
我調試它,看到的按鈕得到正確的輸入,因此應該被啓用,但沒有任何反應。如果用戶停留在開始作業的控件中,則按鈕和進度條的狀態將被正確重置。
在調試過程中您注意到執行控制是否達到'worker_RunWorkerCompleted'? – Nayan 2010-10-08 14:21:29
我在'worker_RunWorkerCompleted'中設置了一個斷點,並且已經達到了。 – danjov 2010-10-08 14:23:35