DownloadStringAync problem

本文关键字:problem DownloadStringAync | 更新日期: 2023-09-27 17:54:54

当我点击提交按钮(一次)时,它不显示给定网站的HTML。当我点击提交按钮(两次),然后它显示html。我认为这可能是因为DownloadStringAsync还没有完成下载网站。

我知道我可以把TextBox。文本到downloadstringcompleted,但我不希望它,因为它将用于类稍后,结果将有一个get/set方法。

如何解决这个问题?下面是我的代码:

    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;
    namespace WebTest
    {
        public partial class MainPage : PhoneApplicationPage
        {
            private string result;
            // Constructor
            public MainPage()
            {
                this.completed = false;
                InitializeComponent();
            }
            private void search_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
            {
                if (e.Error == null)
                {
                    this.result = e.Result;
                }
            }
            private void button1_Click(object sender, RoutedEventArgs e)
            {
                displayHTML(textBox1.Text);
                textBlock1.Text = this.result;
            }
            private void displayHTML(string URL)
            {
                WebClient search = new WebClient();
                search.DownloadStringCompleted += new DownloadStringCompletedEventHandler(search_DownloadStringCompleted);
                search.DownloadStringAsync(new Uri(URL));
            }
        }
    }

DownloadStringAync problem

您正在设置result变量,但不是作用于。这是很好的存储它供以后使用,但如果你想它是显示当网站加载时,这是你应该改变textBlock1.Text -而不是当按钮被点击:

private void search_DownloadStringCompleted(object sender,
                                            DownloadStringCompletedEventArgs e)
{
    if (e.Error == null)
    {
        this.result = e.Result;
        textBlock1.Text = this.result;
    }
}
private void button1_Click(object sender, RoutedEventArgs e)
{
    displayHTML(textBox1.Text);
}