【发布时间】:2011-12-27 12:13:12
【问题描述】:
我正在尝试从我的 Windows Phone 应用程序中使用 json Web 服务,并将检索到的数据显示到列表框中。我能够从 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; }
}
有人可以帮我解决我的问题吗?...在此先感谢。
【问题讨论】:
-
我不知道它是否会解决您的问题,但我会尝试将结果添加到属性并将此属性绑定到您的列表框 ItemsSource ,因此它应该可以工作。我建议你在你的项目中尝试 MVVM。
标签: c# json web-services windows-phone-7.1