WP7 - 更新列表框

时间:2012-05-15 21:32:58

标签: vb.net windows-phone-7 webclient observablecollection

我终于开始启动Windows phone dev了。我还不是很擅长,但无论如何,我希望你们明白我想做什么。

从我从其他程序员那里学到的东西,ObservableCollection可以在实时更新,同时它可以数据绑定到一个对象,例如列表框。对ObservableCollection的所有更改都将导致其数据绑定对象的UI更新其项目。

所以我正在尝试做的是从我的服务器下载文件,用json解析它,然后使用新数据更新ObservableCollection。但是,在重新打开应用程序之前,webclient似乎没有下载新数据!


这是一个显示应用程序如何工作的gif: enter image description here

这是我的代码(减少一点):

Dim aList As New ObservableCollection(Of classes.consoles)

Private Sub PhoneApplicationPage_Loaded(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded
        checkforconsoles()
End Sub

Public Sub checkforconsoles()
        Dim wc As New WebClient()
        AddHandler wc.DownloadStringCompleted, AddressOf downloaded
        wc.DownloadStringAsync(New Uri("http://localhost/api/?function=GetConsolesForUser&userid=" & id))
    End Sub

    Private Sub downloaded(sender As Object, e As DownloadStringCompletedEventArgs)

        aList.Clear()
        'MessageBox.Show(e.Result)

        Dim o As JObject = JObject.Parse(e.Result)

        Dim jarray As JArray = DirectCast(o("results"), JArray)

        Try
            Dim i As Integer = jarray.Count()

            For i = 0 To jarray.Count() - 1 Step 1

                Dim id As String = jarray(i)("id").ToString
                Dim name As String = jarray(i)("name").ToString
                Dim image As String = jarray(i)("image").ToString

                MessageBox.Show(name)

                Dim c As classes.consoles = New classes.consoles()
                c.categoryimage = New Uri(image)
                c.categoryname = name
                c.categoryid = id

                aList.Add(c)
            Next

            listBoxview.ItemsSource = aList
            StackPanel1.Visibility = Windows.Visibility.Collapsed
            StackPanel2.Visibility = Windows.Visibility.Visible

        Catch ex As Exception
            StackPanel2.Visibility = Windows.Visibility.Collapsed
            StackPanel1.Visibility = Windows.Visibility.Visible
        End Try

    End Sub

Private Sub ApplicationBarIconButton_Click_1(sender As System.Object, e As System.EventArgs)
    checkforconsoles()
End Sub

有没有人知道什么是错的? :(

提前致谢。

1 个答案:

答案 0 :(得分:2)

这是WebClient的cachine问题。您可以附加随机查询字符串以确保URL始终是唯一的,以便WebClient不会缓存结果。一种方法是添加随机GUID值,因为它不太可能在短时间内生成两个相同的GUID。

wc.DownloadStringAsync(New Uri("http://localhost/api/?function=GetConsolesForUser&
                         userid=" & id & "&random=" + Guid.NewGuid().ToString()))