调用方法时如何显示ProgressBar

时间:2014-06-04 08:27:39

标签: c# wpf multithreading progress-bar

我想在调用方法时显示ProgressBar,所以我尝试执行此代码:

    if (parametro.chiave == "VIDEO")
    {
       //BISOGNA CARICARE IL VIDEO
       String urlVideo=caricaVideoOnline(parametro.valore);
       ....
    }

    String caricaVideoOnline(string nomeFileVideo)
    {
       try
       {
          libreriaYouTube = new UploadVideo(ConfigurationManager.AppSettings["usernameYoutube"],
                        ConfigurationManager.AppSettings["passwordYouTube"],
                        ConfigurationManager.AppSettings["developmentKeyYouTube"],
                        ConfigurationManager.AppSettings["applicationNameYouTube"]);

         libreriaYouTube.listaVideoToUpload.Add(nomeFileVideo);
         // String video = libreriaYouTube.caricaVideo();
         Thread t = new Thread(delegate()
         {
            for (int i = 0; i < 100000; i++)
            {
               if (i == 0)
               {
                  ProgressBar progress = new ProgressBar();
                  progress.Show();
               }
               Console.WriteLine(i);
            }
         });
         t.SetApartmentState(ApartmentState.STA);
         t.Start();
         String video= libreriaYouTube.caricaVideo();
         video = libreriaYouTube.caricaVideo();
         return video;
      }
      catch (Exception e)
      {
         log.Error(e);
         return null;
      }
   }

此代码已找到,但我显示了ProgressBar,但它已被锁定,我看不到条形图。

这是ProgressBar.xaml的代码

<Window x:Class="Gestore.ProgressBar"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Caricamento video" Height="100" Width="300"
        >
    <Grid Margin="20">
        <ProgressBar Minimum="0" Maximum="100" Name="pbStatus" IsIndeterminate="True" Tag="Attendere....."/>
        <Viewbox>
            <TextBlock Text='Attendere ...' FontSize="2" x:Name="textVox"/>
        </Viewbox>
    </Grid>
</Window>

1 个答案:

答案 0 :(得分:1)

我发现您的代码有几个问题:

  1. 您应该访问pbStatus,而不是在代码中创建新的进度条
  2. 您永远不会更新进度条的值(&#34; pbStatus.Value = ...&#34;)
  3. 您无法从主题t更新进度条。您需要调用应用程序的UI线程才能执行此操作
  4. 循环立即运行。插入一些睡眠语句来控制其计时行为。
  5. 以下示例代码应该可以使用。

    的Xaml:

    <StackPanel Orientation="Vertical">
        <ProgressBar Name="pbStatus" Minimum="0" Maximum="100" Height="20"></ProgressBar>
        <Button Click="ButtonBase_OnClick">Press me</Button>
    </StackPanel>
    

    代码背后:

        private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
        {
            Thread t = new Thread(delegate()
            {
                for (int i = 0; i < 100; i++)
                {
                    this.Dispatcher.Invoke(()=>
                    {
                        pbStatus.Value = i;
                    }); 
                    Thread.Sleep(500);
                }
            });
            t.Start();
        }