我試圖通過在私有異步無效和聲明集合中聲明Posts類的新實例來將一些示例數據添加到可觀察集合中。當應用程序加載時,它不顯示內容。代碼編譯沒有錯誤/警告。添加數據到ObservableCollection時遇到問題
如果我要在Posts()方法中添加樣本數據,那麼它將按預期顯示。
如何從我的私人異步無效填充可觀察集合,並在應用程序啓動時顯示內容?
XAML:
<ListView ItemsSource="{StaticResource Posts}"
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Title}/>
<TextBlock Text="{Binding Author}/>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
C#
public class Data2 {
public string Title { get; set; }
public string Author { get; set; }
public Data2(string title, string author) {
this.Title = title;
this.Author = author;
}
}
public class Posts : ObservableCollection<Data2> {
public Posts() {
}
}
public sealed partial class MainPage : Page {
public MainPage() {
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Required;
GetPosts();
}
protected override void OnNavigatedTo(NavigationEventArgs e) {
}
private async void GetPosts() {
try {
var client = new HttpClient();
var response = await client.GetAsync(new Uri("http://mywebsite.com/posts.json"));
var result = await response.Content.ReadAsStringAsync();
var json = ParseData(result);
Posts posts = new Posts();
posts.Add(new Data2("Sample Title 1", "Sample Author 1"));
posts.Add(new Data2("Sample Title 2", "Sample Author 2"));
}
catch(HttpRequestException hre) {
System.Diagnostics.Debug.WriteLine(hre);
}
catch(Exception ex) {
System.Diagnostics.Debug.WriteLine(ex);
}
}
private static RootObject ParseData(string json) {
return JsonConvert.DeserializeObject<RootObject>(json);
}
}