저는 WP7 용 C#을 사용하여 개발하는 것이 처음입니다. button1을 누를 때 textBox1에서 url을 가져 와서 textBlock1의 텍스트를 해당 페이지의 소스 코드로 업데이트하는 간단한 응용 프로그램을 작성하려고합니다.Windows 전화 응용 프로그램에 대한 웹 페이지 소스 코드 스크랩
내가 붙어있는 부분은 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 전자) { // 요청이 취소되지 않고 // 예외를 throw하지 않은 경우 리소스를 표시합니다. if (! 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을 테스트 할 수는 없습니다. –
나는이 포스트까지 결코 따라 올 수 없다는 것을 깨달았다. 귀하의 조언은 매우 도움이되었고 귀하의 답변에 투표 할 것이지만 나는 새로운 사용자입니다. 답변 해 주셔서 감사합니다. –