【发布时间】:2019-08-31 22:23:14
【问题描述】:
我正在使用 Xamarin 创建一个应用程序,我正在从一个 api 获取数据并尝试在我的视图中显示它,在我的 ListView 中更具体
这是我的xaml 文件
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
x:Class="Reciper2.View.RecetaView">
<ContentPage.Content>
<StackLayout>
<Label Text="Prueba de compartir datos xamarin"
VerticalOptions="Start"
HorizontalOptions="Center">
</Label>
<Label Text="{Binding nombreReceta, StringFormat='Recetas de {0:F0}'}"
VerticalOptions="Center"
HorizontalOptions="CenterAndExpand" />
<Image Source="{Binding fotoReceta}"
VerticalOptions="Center"
HorizontalOptions="CenterAndExpand">
</Image>
<ListView x:Name="listadoRecetas"
VerticalOptions="Center"
HorizontalOptions="StartAndExpand"
ItemsSource="{Binding RecetasList}">
<ListView.ItemTemplate>
<DataTemplate>
<TextCell Detail="{Binding nombre}"
Text="{Binding calorias}">
</TextCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentPage.Content>
我的xaml.cs 文件就是这个。
ObservableCollection<RecetaModel> recetasList = new ObservableCollection<RecetaModel>();
public ObservableCollection<RecetaModel> RecetasList { get { return recetasList; } }
public RecetaView()
{
InitializeComponent();
this.BindingContext = this;
listadoRecetas.ItemsSource = recetasList;
getRecipes();
}
/* protected async override void OnAppearing()
{
getRecipes();
base.OnAppearing();
}*/
public async void getRecipes()
{
var tipoReceta = this.BindingContext as RecetasModel;
if(tipoReceta != null)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));
request.ContentType = "application/json";
request.Method = "GET";
using (WebResponse response = await request.GetResponseAsync())
{
using (Stream stream = response.GetResponseStream())
{
JsonValue jsonDoc = await Task.Run(() => JsonObject.Load(stream));
var jsonString = jsonDoc.ToString();
dynamic objetoRecetas = JsonConvert.DeserializeObject(jsonString);
var listadoRecetas = objetoRecetas.hits;
foreach(dynamic receta in listadoRecetas)
{
dynamic rec = receta.recipe;
string nombre = rec.label;
string imagen = rec.image;
string calorias = rec.calories;
recetasList.Add(new RecetaModel { nombre = nombre, imagen= imagen, calorias = calorias});
}
// await DisplayAlert("Alert", jsonDoc, "OK");
}
}
}
}
这是我的RecetaModel 课程。
public class RecetaModel
{
public string nombre { get; set; }
public string imagen { get; set; }
public string calorias { get; set; }
}
但在我看来没有任何显示。 知道我做错了什么吗? 提前致谢。
【问题讨论】:
-
你为什么要分配
this.BindingContext = this;,然后再做`var tipoReceta = this.BindingContext as RecetasModel;'?那个演员应该永远不会起作用。 -
因为我将数据传递给这个新视图,所以我传递
RecetasModel以供使用
标签: c# xamarin xamarin.forms