DownloadStringAsync获取文本字符串?

时间:2014-07-23 03:18:37

标签: vb.net visual-studio-2010 windows-phone windows-phone-7.1 downloadstring

我正在尝试创建一个Windows Phone 7.1应用程序,基本上是一个货币转换器。我正在使用DownloadStringAsync方法获取包含特定网站汇率的短字符串。我在Visual Studio 2010中测试过,DownloadString工作正常。但不适用于手机应用程序。我需要做什么?我真的无法理解它。

Partial Public Class MainPage
Inherits PhoneApplicationPage
Dim webClient As New System.Net.WebClient
Dim a As String
Dim b As String
Dim result As String = Nothing
' Constructor
Public Sub New()
    InitializeComponent()
End Sub

Private Sub Button1_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles Button1.Click
    a = "USD"
    b = "GBP"
    webClient = New WebClient
    Dim result As String = webClient.DownloadStringAsync(New Uri("http://rate-exchange.appspot.com/currency?from=" + a + "&to=" + b) as String)
    TextBox1.Text = result
End Sub

结束班

2 个答案:

答案 0 :(得分:2)

这里有些不妥之处:

  1. DownloadStringAsync未返回值(C#条款中的void方法)
  2. 您需要处理DownloadStringCompleted变量的WebClient事件。您可以在事件处理程序中获得结果。
  3. 您可以将代码更改为类似内容,以使上述功能正常运行:

    Private Sub Button1_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles Button1.Click
        a = "USD"
        b = "GBP"
        webClient = New WebClient
        'Add the event handler here
        AddHandler webClient.DownloadStringCompleted, AddressOf webClient_DownloadStringCompleted            
        Dim url As String = "http://rate-exchange.appspot.com/currency?from=" & a & "&to=" & b            
        webClient.DownloadStringAsync(New Uri(url))
    End Sub
    
    Private Sub webClient_DownloadStringCompleted(ByVal sender as Object,ByVal e as DownloadStringCompletedEventArgs)
        TextBox1.Text = e.result
    End Sub
    

答案 1 :(得分:0)

只需使用DownloadStringTaskAsync

Using WebClient As WebClient = New WebClient
    Return Await WebClient.DownloadStringTaskAsync(New Uri(myurl))
End Using