进度条在应用中的作用非常大,可以告诉用户当前操作执行的进度,以免用户在等待中失去耐心,进而关闭应用.Windows Phone 7的进度条有两种样式,一种是从左往右循环滚动的小点点,这种进度条并不能显示当前进度,类似于Android进度条的转圈风格;另一种就是能显示进度的普通进度条,两种样式效果如下图:
介绍一下这个实例,页面上三个控件,两个ProgressBar分别显示两种风格的进度条,一个按钮,用于开启新线程更新ProgressBar的进度,这里用于了委托,如有不明白,参考:
几个控件的XAML代码:
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0" Background="{x:Null}">
<ProgressBar Height="54" HorizontalAlignment="Left" Margin="17,27,0,0" Name="progressBar1" VerticalAlignment="Top" Width="390" IsIndeterminate="True" />
<!--IsIndeterminate是关键,这个属性确定了ProgressBar的样式,默认是false,就是普通的能显示进度的进度条,true就是不能显示进度的进度条-->
<ProgressBar Height="59" HorizontalAlignment="Left" Margin="31,107,0,0" Name="progressBar2" VerticalAlignment="Top" Width="374" />
<Button Content="更新progressBar2" Height="82" HorizontalAlignment="Left" Margin="63,199,0,0" Name="button1" VerticalAlignment="Top" Width="260" Click="button1_Click" />
</Grid>
C#程序代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Threading;
namespace PhoneApp3
{
public partial class MainPage : PhoneApplicationPage
{
delegate void ProgressDelegate(int i);
//声明委托类型
//委托的内容如有不明白,见http://www.pocketdigi.com/20110916/476.html 有详细注解
ProgressDelegate progressDelegate;
//声明委托
public MainPage()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
progressDelegate = SetProgress;
//把更新进度方法添加进委托
new Thread(new ThreadStart(ThreadProc)).Start();
//开启新线程
}
private void SetProgress(int i)
{
//这是更新进度条的方法
progressBar2.Value = i;
if (i == 100)
{
//如果达到100,则隐藏进度条
progressBar2.Visibility = Visibility.Collapsed;
//显示方法Visibility.Visibl
}
}
private void ThreadProc()
{//新线程执行的方法
for (int i = 0; i <= 100; i++)
{
this.Dispatcher.BeginInvoke(progressDelegate,i);
//线程中调用委托来更新UI,参数是委托,以及委托的参数
Thread.Sleep(1000);
}
}
}
}