2012-01-22 3 views
1

저는 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; 
      } 
     } 
    } 
} 

답변

2

당신이 원하는 것처럼 당신은 그것을 할 수 없어, WP7 (실버) 알 웹 요청이 비동기 때문이다. 이것은 웹 페이지를 다운로드하는 동안 코드가 멈추지 않고 같은 줄과 함수로 끝나면 새 스레드를 만들고 파일을 다운로드하고 콜백 함수를 호출 함을 의미합니다.

콜백 기능 (귀하의 경우에는 DownloadStringCallback2)을 계속해야합니다. 이 함수에서는 소스 코드 (e.Result)를 텍스트 상자에 넣어야합니다. 혹시 크로스 스레드 예외가 발생하는 경우

는 그에 추가 할 수 있습니다 또는 작업이 실행되는 동안 친절하게 사용할 수있는 UI를 유지하려는 경우, 당신은이 명령을 사용할 수 있습니다

Dispatcher.BeginInvoke(new Action (() => LoadContent("http://www.google.com"))); 

이 명령은 십자가를 해결을 - 올바르게 기억한다면 예외를 수정하고 UI 스레드와 다른 스레드에서 코드를 실행하여 안정적인 UI를 유지합니다. 지금과 같이 할 수있는 콜백 함수 업데이트

private void button1_Click(object sender, RoutedEventArgs e) 
    { 
     string url = textBox1.Text; 
     LoadSiteContent(url); 
    } 

    public string LoadSiteContent(string url) 
    { 
     //create a new WebClient object 
     WebClient client = new WebClient(); 

     client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(DownloadStringCallback2); 
     client.DownloadStringAsync(new Uri(url)); 
    } 

    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) 
     { 
      textBlock1.Text = (string)e.Result; 
      //If you get the cross-thread exception then use the following line instead of the above 
      //Dispatcher.BeginInvoke(new Action (() => textBlock1.Text = (string)e.Result)); 
     } 
    } 
+0

:

편집 내가 당신의 코드는 다음과 같이해야한다고 생각 '개인 정적 무효 DownloadStringCallback2 (개체 보낸 사람, DownloadStringCompletedEventArgs 전자) { // 요청이 취소되지 않고 // 예외를 throw하지 않은 경우 리소스를 표시합니다. if (! e.Cancelled && e.Error == null) { textBlock1.Text = (string) e.Result; } }' 내가 오류를 얻고있다 : 객체 참조가 비 정적 필드, 메서드 또는 속성에 필요한 'TestApp1.MainPage.textBlock1' 내가 뭘 잘못 어떤 생각을 가지고 있습니까? –

+0

MainPage에있는 textBlock1을 편집하려고하고 있으며 콜백 함수가 정적이기 때문에 textBlock1을 알지 못하는 이유입니다. 이 문제를 다루는 나의 방법은 대의원을 사용하는 것이었다. 위임자는 비동기 이벤트 때문에 wp7에서 정말 유용합니다. 내가 알지 못하는 경우 위임자를 찾아 보는 것이 좋습니다. 'public static MainPage mainPage;를 추가하여'mainPage = this;'처럼 생성자에 입력하면'mainPage.textBlock1.Text = (string) e.Result; '로 textBlock1을 채울 수 있습니다. . 더 쉬운 방법이있을 수 있지만 atm을 테스트 할 수는 없습니다. –

+0

나는이 포스트까지 결코 따라 올 수 없다는 것을 깨달았다. 귀하의 조언은 매우 도움이되었고 귀하의 답변에 투표 할 것이지만 나는 새로운 사용자입니다. 답변 해 주셔서 감사합니다. –

관련 문제