【发布时间】:2020-03-17 10:05:35
【问题描述】:
我不知道这是怎么做到的。我在每个单元格内都有一个带有集合视图和图像的页面。 我也有一个 URL 列表,每个 URL 都指向一个 jpg。我想做的是在其中一个单元格中显示每个 jpg。
<StackLayout Margin="20">
<CollectionView ItemsSource="{Binding UrlCollection}">
<CollectionView.ItemsLayout>
<GridItemsLayout Orientation="Vertical"
Span="2" />
</CollectionView.ItemsLayout>
<CollectionView.ItemTemplate>
<DataTemplate>
<Image Source="{Binding ImageUrl}"
Aspect="AspectFill" />
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
</StackLayout>
到目前为止,在我看来,我必须创建一个名为 UrlCollection 的类,并且该类中的一个项目是 ImageUrl。但是我感到迷茫,找不到可以效仿的例子。
更新我当前的版本。它不工作,显示只是空白。
图库.xaml
<?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:vm="clr-namespace:GalShare.ViewModel"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
x:Class="GalShare.Views.Gallery">
<ContentPage.BindingContext>
<vm:GalleryViewModel/>
</ContentPage.BindingContext>
<StackLayout>
<CollectionView ItemsSource="{Binding Gallery}">
<CollectionView.ItemsLayout>
<GridItemsLayout Orientation="Vertical"
Span="2" />
</CollectionView.ItemsLayout>
<CollectionView.ItemTemplate>
<DataTemplate>
<Image Source="{Binding ImageUrl}"
Aspect="AspectFit" />
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
</StackLayout>
图库.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace GalShare.Model
{
class Gallery
{
public string ImageName { get; set; }
public string ImageUrl { get; set; }
}
}
GalleryService.cs
using GalShare.Model;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
namespace GalShare.Service
{
class GalleryService
{
public ObservableCollection<Gallery> GetImageList()
{
return new ObservableCollection<Gallery>()
{
new Gallery() { ImageName="Image1", ImageUrl="https://www.igormasin.it/fileuploads/tanja_23a6id/IMG_0992-Edit_a.jpg"},
new Gallery() { ImageName="Image2", ImageUrl="https://www.igormasin.it/fileuploads/tanja_23a6id/IMG_1024-Edit_a.jpg"},
new Gallery() { ImageName="Image3", ImageUrl="https://www.igormasin.it/fileuploads/tanja_23a6id/IMG_1074-Edit_a.jpg"}
};
}
}
}
GalleryViewModel.cs
using GalShare.Model;
using GalShare.Service;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
namespace GalShare.ViewModel
{
class GalleryViewModel
{
public ObservableCollection<Gallery> Images { get; set; }
public GalleryViewModel()
{
Images = new GalleryService().GetImageList();
}
}
}
主页调用:
MainPage = new NavigationPage(new Gallery());
【问题讨论】:
-
您是否将 BindingContext 设置为 ViewModel 类。如果是,请添加 ViewModel 类进行查询。
-
@Nikhileshwar ,您在聊天中提到界面可能会锁定,请您看看这个? stackoverflow.com/questions/60804577/…谢谢
标签: image xamarin collectionview itemsource