zsyzhou 发表于 2015-5-23 10:23:10

Windows Phone 8 下载文件进度

  后台代码:
public partial class MainPage : PhoneApplicationPage
{
private long siz;
private long speed;
private Stopwatch sw;
private Stopwatch sw1;
public MainPage()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
testspeed();
}
public void testspeed()
{
WebClient client = new WebClient();
progressBar1.Value = 0.0;
textBox2.Text = "0 %";
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(this.webClient_DownloadStringCompleted);
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(this.webClient_DownloadProgressChanged);
sw = Stopwatch.StartNew();//用来记录总的下载时间
sw1 = Stopwatch.StartNew();//用来记录下载过程中的时间片,用于计算临时速度
client.DownloadStringAsync(new Uri("http://dl_dir.qq.com/qqfile/qq/QQ2011/QQ2011.exe"));
}
//下载过程事件
public void webClient_DownloadProgressChanged(object s, DownloadProgressChangedEventArgs e)
{
textBox2.Text = e.ProgressPercentage.ToString() + " %";
sw1.Stop();
long num = e.BytesReceived / 1024;
if (sw1.Elapsed.Seconds != 0)
{
speed = num / ((long)sw1.Elapsed.Seconds);
}
textBlock4.Text = this.speed + " KB/s";
progressBar1.Value = e.ProgressPercentage;
siz = e.TotalBytesToReceive;
textBlock3.Text = siz/1024/1024 + "MB";
sw1.Start();
}
//下载完成事件
public void webClient_DownloadStringCompleted(object s, DownloadStringCompletedEventArgs e)
{
sw.Stop();
siz = siz / 1024;
long num = siz / ((long)sw.Elapsed.Seconds);
sw.Reset();
textBox1.Text = "下载完成!";
textBlock1.Text = num + " KB/s";
}
}
}

  XAML 设计代码:






























  运行结果图:
   
页: [1]
查看完整版本: Windows Phone 8 下载文件进度