我遇到一个问题,我的ListView没有显示任何数据。我正在尝试在ListView中加载ImageUrls(作为文本)。我的视图(在.xaml中)在StackLayout中包含以下代码:
<?xml version="1.0" encoding="UTF-8"?>
<ContentPage
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:viewModels="clr-namespace:App.ViewModels"
xmlns:abstractions="clr-namespace:RoundedBoxView.Forms.Plugin.Abstractions;assembly=RoundedBoxView.Forms.Plugin.Abstractions"
xmlns:iconize="clr-namespace:FormsPlugin.Iconize;assembly=FormsPlugin.Iconize"
x:Class="App.Views.ProductDetailView" >
<ContenPage.Content>
<StackLayout Spacing ="0"
BackgroundColor="White">
<ListView ItemsSource="{Binding Images}"
HasUnevenRows="True">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout HorizontalOptions="Start" >
<Label x:Name="URRl"
Text="{Binding Url}"
TextColor="Navy"
FontSize="20"/>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentPage.Content>
</ContentPage>
我的ViewModel(.cs)如下:
public class ProductDetailViewModel : INotifyPropertyChanged
{
//event
public event PropertyChangedEventHandler PropertyChanged;
public ObservableCollection<ImageList> images;
//The variables which are binded to the View.
public ObservableCollection<ImageList> Images
{
get
{
return images;
}
set
{
if(images != value)
{
images = value;
foreach (ImageList il in images)
Console.WriteLine(il.Url);
OnPropertyChanged();
}
}
}
/// <summary>
/// Initializes a new instance of the <see cref="T:App.ViewModels.ProductDetailViewModel"/> class.
/// Listens for a message with the id of the product
/// </summary>
public ProductDetailViewModel(IRestService<ProductDetailsPhoto, ProductList> api)
{
//Images is being set here
}
/// <summary>
/// Notify INotifyPropertyChanged with the propertyName
/// </summary>
/// <param name="propertyName">Property name of the changed Variabele</param>
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public class ImageList
{
public string Url;
public ImageList(string _url)
{
Url = _url;
}
}
背后的ProductDetailView代码
public partial class ProductDetailView : ContentPage
{
public ProductDetailView(int productID)
{
InitializeComponent();
BindingContext = App.ProductDetailsVM;
MessagingCenter.Send(this, Constants.GET_PRODUCT_DETAILS, productID);
}
}
我测试了将数据加载到Images中的函数。数据已正确加载。
实际行为 视图显示一个不包含数据的空列表。
预期行为 在ListView中将图像URL显示为文本的视图。
任何人都可以告诉我,我的数据绑定或在我的视图中我做错了什么?如果您需要其他一些代码或有其他问题,请询问。
答案 0 :(得分:2)
您无法绑定到某个字段。将Url
课程中的ImageList
字段更改为媒体资源:
public class ImageList
{
public string Url {get; set;}
public ImageList(string _url) {
Url = _url;
}
}