2011-08-17 201 views
1

我正在爲我的WPF應用程序添加一個進度條。我想告訴與生成文件的實時計數一起在進度條上的實時進展情況等產生4/100文件等下面是這兩個動作和任務正在執行這些行動WPF實時進度條

 Action Generate = new Action(() => 
      { 
       foreach (string file in Files) 
       {     

      //all the logic to generate files 


        using (var streamWriter = new StreamWriter(newFileName, false, Encoding.Default)) 
        { 
         foreach (string segment in newFile) 
         { 
          streamWriter.WriteLine(segment); 
         } 
         filesGenerated++; 

       //I need to do the second action here      
        } 

       } 
      }); 


    Action ShowProgressBar = new Action(() => 
      { 
       progressBar.Value = filesGenerated 
    lblProgress.Content = filesGenerated + " File(s) Generated."; 

      }); 

    Task GenerateTask = Task.Factory.StartNew(() => Generate()); 

    Task ShowProgressBarTask = new Task(ShowProgressBar); 

我試圖嵌套的任務,但它不工作。我應該做些什麼來顯示實時進度條。

+0

請使用擴展WPF工具包,它具有BusyIndi​​cator控件元素:CodePlex項目(http://wpftoolkit.codeplex.com/)BusyIndi​​cator控件文件](http://wpftoolkit.codeplex.com/wikipage?title=BusyIndi​​cator&referringTitle=Home) – Rumplin 2011-08-17 12:43:18

回答

3
  1. 在另一個線程

  2. 由另一個線程使用Dispatcher,因爲你坐落在foreach循環進度條的值運行你的文件創建代碼,並不能改變從一個UI控件。

基本上你完成了。

0

看看我在BackgroundWorker herehere上的答案。

實質上,您將使用BackgroundWorker的方法和事件將文件創建移動到另一個線程,並在UI線程中報告進度。

-1
public static class Refresh 

    { 
     public static void Refresh_Controls(this UIElement uiElement) 
     { 
      uiElement.Dispatcher.Invoke(DispatcherPriority.Background, new Action(() => { })); 
     } 
    } 

在主代碼:

Refresh.Refresh_Controls(progressBar1);