![](/img/trans.png)
[英]Xamarin.Forms unable to bind ObservableCollection to CollectionList via ViewModel
[英]Unable to Deserialize json into an ObservableCollection and bind to xaml in Xamarin.Forms
我正在嘗試將簡單的json反序列化為ObservableCollection。 當我為反序列化設置斷點時,似乎什么也沒有發生。 該方法永遠不會完成,也不會引發錯誤。 我能夠獲取json並轉換為字符串,只是不反序列化為ObservableCollection。
我想念什么嗎? 我看了我能找到的用於反序列化對象的每個代碼示例,但似乎無法使其工作。
這是我的Xamarin.Forms頁面的代碼。
public partial class Notification : ContentPage
{
public Notification()
{
InitializeComponent();
this.BindingContext = NotificationData();
}
public async Task NotificationData()
{
ObservableCollection<Alert> notification = await GetAlert();
NotificationList.ItemsSource = notification;
}
public static async Task<ObservableCollection<Alert>> GetAlert()
{
string WPPosts = "https://www.url.com/alerts.json";
HttpClient client = new HttpClient();
var response = await client.GetAsync(WPPosts).ConfigureAwait(false);
if (response != null)
{
ObservableCollection<Alert> data = new ObservableCollection<Alert>();
string content = response.Content.ReadAsStringAsync().Result;
//string content_sanitized = RemoveHTMLTags(content);
data = JsonConvert.DeserializeObject<ObservableCollection<Alert>>(content);
return data;
}
else { return null; }
}
public class Alert
{
public string title { get; set; }
public string imgUrl { get; set; }
public string content { get; set; }
}
public class RootObject
{
public List<Alert> alerts { get; set; }
}
}
這是我的Xaml。
<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" Title="News
and Alerts" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="JenksTrash.Notification" xmlns:local="clr-
namespace:JenksTrash" >
<ListView x:Name="NotificationList">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1" />
<ColumnDefinition Width="7*" />
</Grid.ColumnDefinitions>
<Label Text="{Binding title}" FontAttributes="Bold" />
<Label Text="{Binding content}" FontAttributes="Bold" />
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
任何幫助理解這一點將是驚人的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.