[英]how to display complete data in a listbox in windows phone 7 application
[英]unable to display data from json webservice in listbox of windows phone 7.1 application
我正在尝试从Windows Phone应用程序使用json网络服务,并将检索到的数据显示在列表框中。 我能够从Web服务获取数据(在e.result中),但是,我无法在列表框中获取数据。 以下是我的xaml代码。
<Grid x:Name="ContentPanel" Grid.Row="2" Margin="12,0,12,0">
<Grid.Background>
<SolidColorBrush Color="Black" >
</SolidColorBrush>
<!--<ImageBrush ImageSource="/images/BG@.png" 5F91F5/>-->
</Grid.Background>
<ListBox x:Name="carslist" Padding="0,0,0,0" HorizontalAlignment="Center" VerticalAlignment="Top" >
<ListBox.ItemTemplate>
<DataTemplate>
<Border Margin="3" Height="50">
<StackPanel Background="Transparent" Orientation="Vertical" Width="420" Height="60">
<StackPanel Background="Transparent" Orientation="Horizontal" Width="420" Height="60">
<TextBlock Foreground="White" HorizontalAlignment="Left" TextWrapping="NoWrap" VerticalAlignment="Center" FontSize="26" Text="{Binding cartype}"/>
<TextBlock Foreground="White" HorizontalAlignment="Left" TextWrapping="NoWrap" VerticalAlignment="Center" FontSize="26" Text="{Binding carcode}"/>
</StackPanel>
</StackPanel>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
以下是我的xaml.cs代码。
public MainPage()
{
InitializeComponent();
string key = "123";
WebClient getcars = new WebClient();
getcars.DownloadStringCompleted += new DownloadStringCompletedEventHandler(getcars_DownloadStringCompleted);
getcars.DownloadStringAsync(new Uri("http://myurl?key=" + "{" + key + "}"));
}
void getcars_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
Stream stream = new MemoryStream(Encoding.Unicode.GetBytes(e.Result));
DataContractJsonSerializer obj = new DataContractJsonSerializer(typeof(List<cars>));
List<cars> result = obj.ReadObject(stream) as List<cars>;
carslist.ItemsSource = result;
}
}
public class cars
{
public string carcode { get; set; }
public string cartitle { get; set; }
public string cartype { get; set; }
public string carid { get; set; }
}
有人可以帮我解决我的问题吗?...谢谢。
很明显为什么它不起作用。 List<cars> result
将作为getcars_DownloadStringCompleted处理程序内部的局部变量创建,并具有该处理程序的本地作用域,因此在该处理程序完成时会立即对其进行垃圾回收。 这就是为什么您看不到任何数据的原因。
为了解决这个问题,例如在页面上创建公共属性
public ObservableCollection<cars> Results {get;set;}
并在getcars_DownloadStringCompleted处理程序中将您的结果添加到该Results集合中。 然后在代码中执行此操作:
carslist.ItemsSource = this.Results;
它应该工作。
在添加“结果”集合之前,还请确保从JSon服务反序列化的项目有效。 我会在将调试器中的断点放在您将结果分配给Results集合的行中,并确保确实在其中添加了某些内容。
如果您问我,也应该在cars类中实现InotifyPropertyChanged。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.