我正在创建一个用于下载文件的类。我从WebClient中找到了一个代码片段,但它只有一个类(主类)。 是否有可能编写一个可以将事件附加到主类的控件的类,以便他们只需要设置下载类,然后它就可以从分配给它的任何内容中附加自己吗
我相信有一种比从类中调用线程循环进度变量更好的方法。
示例:
public partial class Main : Window
{
public Main()
{
InitializeComponent();
}
private void reportProgress() {
Class1 cls1 = new Class1();
// Some thread invoking here
while (true)
progressBar1.Value = cls1.progressValue;
}
}
public class Class1
{
public int progressValue = 0;
public void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
progressValue.Value = e.ProgressPercentage;
}
}
WebClient Snippet(仅在主类中,因此您可以直接将其附加到控件):
private void DownloadFile()
{
using (WebClient webClient = new WebClient())
{
webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
try
{
// Start downloading the file
webClient.DownloadFileAsync(new Uri("http://website.com/file.exe"),
"filename.exe",
"E:\\");
}
catch (WebException ex)
{
throw new WebException(ex.Message);
}
}
}
public void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
提前致谢。
答案 0 :(得分:0)
下载可以在另一个类中,但是您需要在Window代码隐藏中为WebClient添加一些代码。
class Downloader
{
internal WebClient Client { get; set; }
internal Downloader() {
WebClient client = new WebClient();
Client = client;
}
internal void DownloadFile( string uri, string path ) {
using ( Client ) {
Client.DownloadFileAsync( new Uri(uri), path );
}
}
}
在窗口代码隐藏中,您需要获取Client
和钩子事件。就是这样。