2011-08-17 47 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);