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。 –
我剛剛意識到我從未跟進過這篇文章。你的建議是非常有用的,我會投你的答案,但我是一個新用戶。感謝您的答覆。 –