搜尋此網誌

2009年12月28日 星期一

Silverlight:下載進度

1、先在 .xaml 檔內的UserControl加入以下程式碼:

<Grid x:Name="LayoutRoot" Height="100" Width="300" Loaded="downloadObj">
 <Rectangle Fill="Black" />
 <Rectangle x:Name="bg"  Fill="Red" Height="20" Width="200"
  HorizontalAlignment="Left" Margin="50,0"/>
 <Rectangle x:Name="bar" Fill="Yellow" Height="20" Width="1"
  HorizontalAlignment="Left" Margin="50,0"/>
 <TextBlock x:Name="progressText" Text="0%" FontSize="15"
  Foreground="White" HorizontalAlignment="Center"
  VerticalAlignment="Center"/>
</Grid>


2、接著生出一個檔案,將檔案放到專案的「ClientBin/」之下(與xap檔案同資料夾,在此以SilverlightVideoPlayerClassLibrary.zip為例)
3、在.cs檔寫入以下程式碼:

private void downloadObj(object sender, RoutedEventArgs e)
{
 WebClient wc = new WebClient();
 wc.DownloadProgressChanged +=
   new DownloadProgressChangedEventHandler(wc_DownloadProgressChanged);
 wc.OpenReadCompleted += new OpenReadCompletedEventHandler(wc_OpenReadCompleted);
 wc.OpenReadAsync(new Uri("SilverlightVideoPlayerClassLibrary.zip",
           UriKind.Relative));
}

void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
 if (e.Error == null)
 {

 }
 else
 {
  MessageBox.Show("error : " + e.Error.ToString());
 }
}

void wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
 bar.Width = (double) e.ProgressPercentage * 2;
 progressText.Text = e.ProgressPercentage.ToString() + "%";
}


progressText為TextBlock元件,在此利用WebClient做到檔案下載的動作,以event handler取得下載進度,反應於 wc_DownloadProgresshanged中。

沒有留言:

張貼留言