![](/img/trans.png)
[英]Webclient + UploadStringAsync + Events: UploadProgressChanged / DownloadProgressChanged
[英]Update invoking class with Webclient events
我有一個WPF應用程序,其中的viewmodel(mainviewmodel)包含一個方法DownloadFile()。
在這種情況下,刪除一些不感興趣的代碼,如下所示:
class MainViewModel() {
private async void DownloadFile(Object obj)
{
var file = (SharepointFile)obj;
ISharepointServer server;
if (file.isSharepoint365())
{
server = new Sharepoint365();
}
else
{
server = new Sharepoint2013();
}
file = server.DownloadFileFromServer(file);
}
}
我的DownloadFileFromServer(file)看起來像這樣:
class Sharepoint2013 {
public SharepointFile DownloadFileFromServer(SharepointFile sharepointfile) {
WebClient client = new WebClient();
Uri uri = new Uri(file.remoteUrl);
// Download file
client.Credentials = CredentialCache.DefaultCredentials;
client.DownloadFileAsync(uri, filename);
// Save parameters
file.localname = filename;
file.localmajorversion = file.majorversion;
file.localminorversion = file.minorversion;
file.updatesavailable = false;
return file;
}
}
我的問題是如何使用來自Webclient(DownloadProgressChanged和DownloadFileCompleted)的事件來更新gui。 它必須是用於更新UI的mainviewmodel(調用類)。
我應該建立在傳播WebClient的事件來調用類的被叫類的事件? 還是有辦法將原始事件從Web客戶端傳播到調用類?
請注意,這些類的Sharepoint2013和Sharepoint365名稱與問題無關,它們是在開發期間命名的。 讓我記住什么是什么。
沒測試過,但是回調可能對您有用? 我寧願使用HttpClient,但如果您必須...
class Sharepoint2013 {
public SharepointFile DownloadFileFromServer(SharepointFile sharepointfile, Action<file> onCompleted) {
WebClient client = new WebClient();
client.DownloadFileCompleted += () =>
{
// Do your "Save" stuff here and then call the callback.
// Save parameters
file.localname = filename;
file.localmajorversion = file.majorversion;
file.localminorversion = file.minorversion;
file.updatesavailable = false;
//return file;
onCompleted?.Invoke(file);
}
Uri uri = new Uri(file.remoteUrl);
// Download file
client.Credentials = CredentialCache.DefaultCredentials;
client.DownloadFileAsync(uri, filename);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.