私はWP7用のC#で開発するのが非常に新しいです。私は、テキストボックス1からurlを受け取り、button1が押されたときに、そのページのソースコードでtextBlock1のテキストを更新する簡単なアプリケーションを作成しようとしています。Windows PhoneアプリケーションのWebページソースコードを掻き集める
私が取り組んでいるのは、DownloadStringCallback2のResultを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;
}
}
}
}
要求がキャンセルされず、 //例外をスローしなかった場合は、リソースを表示します。 if(!e.Cancelled && e.Error == null) { textBlock1.Text =(文字列)e.Result; }} ' 私はエラーを取得しています :オブジェクト参照が非静的フィールド、メソッド、またはプロパティのために必要とされる「TestApp1.MainPage.textBlock1」 あなたは私が間違っているの何任意のアイデアを持っていますか? –
メインページにあるtextBlock1を編集しようとしていることと、コールバック関数が静的であるためtextBlock1が認識されないためです。これに対処する私の方法は代理人を使用していました。代理人は非同期イベントのためにwp7で本当に便利です。私はあなたに知られていない場合はそれらを検索することをお勧めします。 'public static MainPage mainPage;を' mainPage = this; 'のようにコンストラクタに入れて、' mainPage.textBlock1.Text =(string)e.Result;でtextBlock1を塗りつぶすこともできます。 。より簡単な方法があるかもしれませんが、私はatmをテストすることはできません。 –
私はちょうど私がこの記事に追いついたことがないことに気づいた。あなたのアドバイスはとても役に立ちました。私はあなたの答えを投票しますが、私は新しいユーザーです。回答いただきありがとうございます。 –