1
我对用WP7开发C#是非常新的。我正在尝试编写一个简单的应用程序,它将从textBox1中获取URL,并在button1被按下时使用该页面的源代码更新textBlock1中的Text。为windows phone应用程序刮去网页源代码
我坚持的部分是如何将DownloadStringCallback2中的结果传递回LoadSiteContent函数,以便它可以作为变量sourceCode返回。
代码如下:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
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 TestApp1
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
string url = textBox1.Text;
string sourceCode = LoadSiteContent(url);
textBlock1.Text = sourceCode;
}
/// <summary>
/// method for retrieving information from a specified URL
/// </summary>
/// <param name="url">url to retrieve data from</param>
/// <returns>source code of URL</returns>
public string LoadSiteContent(string url)
{
//create a new WebClient object
WebClient client = new WebClient();
//create a byte array for holding the returned data
string sourceCode = "Fail";
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(DownloadStringCallback2);
client.DownloadStringAsync(new Uri(url));
//use the UTF8Encoding object to convert the byte
//array into a string
//UTF8Encoding utf = new UTF8Encoding();
//return the converted string
//return utf.GetString(html, 0, html.Length);
return sourceCode;
}
private static void DownloadStringCallback2(Object sender, DownloadStringCompletedEventArgs e)
{
// If the request was not canceled and did not throw
// an exception, display the resource.
if (!e.Cancelled && e.Error == null)
{
string textString = (string)e.Result;
}
}
}
}
我更新的回调函数,以现在的样子: '私有静态无效DownloadStringCallback2(对象发件人,DownloadStringCompletedEventArgs E) {// 如果请求未被取消,并且没有抛出 //异常,则显示该资源。如果(!e.Cancelled && e.Error == null) { textBlock1.Text =(string)e.Result; } }' 我收到错误:是必需的非静态字段,方法或属性的对象引用“TestApp1.MainPage.textBlock1” 你有任何想法,我做错了什么? –
之所以这样说,是因为你想编辑MainPage上的textBlock1,而且因为你的回调函数是静态的,所以它不知道textBlock1。我处理这个问题的方法是使用委托。由于异步事件,代表在wp7中非常有用,我建议您在他们不知道的情况下查看它们。你也可以添加一个'public static MainPage mainPage;'并将其填充到像mainPage = this这样的构造函数中,然后你可以用'mainPage.textBlock1.Text =(string)e.Result'来填充textBlock1; 。可能有更简单的方法,但我无法测试atm。 –
我刚刚意识到我从未跟进过这篇文章。你的建议是非常有用的,我会投你的答案,但我是一个新用户。感谢您的答复。 –