[英]Show List in Xamarin consuming REST API
我想顯示使用API的Xamarin(VS 2017)中的產品列表,但是在運行我的應用程序時,它向我顯示了一個空列表(如圖中所示)
對於上述情況,我通過POSTMAN驗證了該服務可供使用
然后創建一個名為ApiServices的服務,該服務使用API:
APISERVICE.CS:
public async Task<Response> GetList<T>(string urlBase, string servicePrefix, string controller)
{
try
{
var client = new HttpClient();
client.BaseAddress = new Uri(urlBase);
var url = string.Format("{0}{1}", servicePrefix, controller);
var response = await client.GetAsync(url);
var result = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode)
{
return new Response
{
IsSuccess = false,
Message = result,
};
}
var list = JsonConvert.DeserializeObject<List<T>>(result);
return new Response
{
IsSuccess = true,
Message = "Ok",
Result = list,
};
}
catch (Exception ex)
{
return new Response
{
IsSuccess = false,
Message = ex.Message,
};
}
}
然后,在我的ProductsViewModel中,我調用GetList方法並傳遞參數:
PRODUCTOSVIEWMODEL.CS:
public ObservableCollection<Product> Productos { get { return this.productos; }
set { this.SetValue(ref this.productos, value); }
}
private ObservableCollection<Product> productos;
private ApiService apiService;
public ProductosViewModel()
{
this.apiService = new ApiService();
this.LoadProductos();
}
private async void LoadProductos()
{
var response = await this.apiService.GetList<Product>("https://salesapiservices.azurewebsites.net", "/api", "/Products");
if (!response.IsSuccess)
{
await Application.Current.MainPage.DisplayAlert("Error", response.Message, "Aceptar");
return;
}
var list = (List<Product>)response.Result;
Productos = new ObservableCollection<Product>(list);
}
最后,在我看來,我展示了我想要的元素:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="Fundamentos.Views.ProductosPage"
BindingContext="{Binding Main, Source={StaticResource Locator}}"
Title="Productos">
<ContentPage.Content>
<StackLayout
BindingContext="{Binding Productos}"
Padding="4">
<ListView
ItemsSource="{Binding Productos}">
</ListView>
</StackLayout>
</ContentPage.Content>
</ContentPage>
我附上我的產品型號:
public class Product
{
public int ProductId { get; set; }
public string Description { get; set; }
public string Remarks { get; set; }
public string ImagePath { get; set; }
public Decimal Price { get; set; }
public bool IsAvailable { get; set; }
public DateTime PublishOn { get; set; }
public string ImageFullPath
{
get
{
if (string.IsNullOrEmpty(this.ImagePath))
{
return "noproduct";
}
return $"https://salesbackend.azurewebsites.net/{this.ImagePath.Substring(1)}";
}
}
public override string ToString()
{
return this.Description;
}
}
我驗證JSON是否到達:
值得一提的是,我正在使用MVVM模式,並且已經在MainViewModel中實例化了ProductsViewModel類,並且已經查看了代碼,但找不到錯誤!
對我有幫助嗎? 請繼續關注您的評論
由於要綁定到ListView
的模型是復雜類型,因此需要為ListView
定義自定義布局
您可以參考以下代碼:
<ListView ItemsSource="{Binding Productos}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Label Text="{Binding Description}"
FontSize="Large"
FontAttributes="Bold"
HorizontalTextAlignment="Start"
Margin="20,0,0,0"
VerticalTextAlignment="Center"
>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.