2014-02-23 62 views
1

我正在创建一个用于下载文件的类。我从WebClient中找到了一个相同的代码片段,但只有一个类(主类)。 是否有可能编写一个类可以将一个事件附加到主类的控件上,这样他们所需要的就是设置下载类,然后只需将它自己分配给它的任何东西?从另一个类下载进度条

我相信有比从类中调用线程循环进度变量更好的方法。

实施例:预先

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; 
    } 

感谢:

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; 
    } 
} 

Web客户端片段(仅在主类因此可以将其直接连接到一个控制)。

回答

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,并且钩事件。就这样。