我一直在寻找一种方法来创建一个很好的进度条.我找到了一些我用过的代码,如果我使用了循环,它的效果很好.但现在我想在一个真正体面的应用程序中使用它,它给了我很多麻烦.我有一个应用程序,我在IMDB上查找数据,所以我连接到IMDB例如500 movietitles,所以这需要一段时间.所以我想展示一个进度条,其中每个电影的条形图都会增长,并且在movietitle上有一些额外的信息.
我使用以下类:
public partial class ProgressDialog : Window, IProgressContext
{
public ProgressDialog()
{
InitializeComponent();
IconBitmapDecoder ibd = new IconBitmapDecoder(
new Uri("IMDB.ML.ico", UriKind.RelativeOrAbsolute),
BitmapCreateOptions.None, BitmapCacheOption.Default);
this.Icon = ibd.Frames[0];
}
public void UpdateProgress(double progress)
{
Dispatcher.BeginInvoke(DispatcherPriority.Background,
(SendOrPostCallback)delegate { Progress.SetValue(ProgressBar.ValueProperty, progress); }, null);
}
public void UpdateStatus(string status)
{
Dispatcher.BeginInvoke(DispatcherPriority.Background,
(SendOrPostCallback)delegate { StatusText.SetValue(TextBlock.TextProperty, status); }, null);
}
public void Finish()
{
Dispatcher.BeginInvoke(DispatcherPriority.Background,
(SendOrPostCallback)delegate { Close(); }, null);
}
}
public interface IProgressContext
{
void UpdateProgress(double progress);
void UpdateStatus(string status);
void Finish();
}
Run Code Online (Sandbox Code Playgroud)
这是使用进度条的imdb查找方法,此方法使用现有的xml列表,因此它仅用于更新数据,而不是添加新电影:
public static void updateIMDBinfo()
{
//initialize progressbar
ProgressDialog myProgressContext = new ProgressDialog();
myProgressContext.Show();
//load old list
List<Movie> movieList = XML.getMovieList();
//create new updated list
List<Movie> newMovieList = new List<Movie>();
int count = 1;
foreach (Movie movie in movieList)
{
//update progressbar
myProgressContext.UpdateProgress((double)count / (double)movieList.Count);
myProgressContext.UpdateStatus(String.Format("Updating movie: '{0}' ({1}/{2})", movie.Title, count, movieList.Count));
movie.Link = movie.Link.Substring(movie.Link.IndexOf("http://www.imdb.com/title/") + 26, 9);
//this creates a new movie where it looks up the data from imdb
newMovieList.Add(new Movie(movie.Title, movie.Link, movie.Path));
count++;
}
//sort the list
newMovieList.Sort((Movie m1, Movie m2) => m1.Title.CompareTo(m2.Title));
//save as xml
XML.updateMovieList(newMovieList);
//finish progressbar
myProgressContext.Finish();
}
Run Code Online (Sandbox Code Playgroud)
因此,现在当我使用该方法时,它会打开进度条,但是条形图永远不会填充,它只是不断添加电影到列表并查找更新的信息而不填充条形图.我认为通过在不同的威胁中使用它会解决这个问题吗?
有任何想法吗?
谢谢一堆
编辑:
我尝试使用BackgroundWorker.我在我的方法中添加了一个后台工作程序并返回一个ReportProgress.我还在我的主类中添加了一个backgroundWorker,它使用了带有eventhandler的方法.然而,它没有奏效.我不太熟悉不同的威胁.那我该怎么办呢?我在这里尝试过:
http://msdn.microsoft.com/en-us/library/cc221403(VS.95).aspx