Reputation: 327
I want to display list of images as a grid with several rows (2 or 4) with Xamarin Forms. Each cell of the grid must be square. I'm using CollectionView with vertical layout, required span and fixed HeightRequest in DataTemplate. I get multicolumn grid, but I cannot make images (cells) to be squared.
<CollectionView ItemsSource="{Binding .}">
<CollectionView.ItemsLayout>
<GridItemsLayout Orientation="Vertical" Span="2" />
</CollectionView.ItemsLayout>
<CollectionView.ItemTemplate>
<DataTemplate>
<Image
HeightRequest="100"
x:Name="imageCell"
Aspect="AspectFill"
Source="{Binding .}" />
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
Upvotes: 2
Views: 4172
Reputation: 327
Thanks to other answers, I've ended up with custom ContentView setting up HeightRequest equal to Width and the image inside it.
public class SquareView : ContentView
{
protected override void OnSizeAllocated(double width, double height)
{
base.OnSizeAllocated(width, height);
HeightRequest = Width;
}
}
and XAML
<CollectionView
ItemsSource="{Binding .}">
<CollectionView.ItemsLayout>
<GridItemsLayout
Orientation="Vertical"
Span="2" />
</CollectionView.ItemsLayout>
<CollectionView.ItemTemplate>
<DataTemplate>
<views:SquareView>
<Image
HeightRequest="20"
Aspect="AspectFill"
Source="{Binding .}" />
</views:SquareView>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
Upvotes: 5
Reputation: 787
Don't use <Image></Image>
as your root layout in DataTemplate.
Instead, use one of the Layout controls (StackLayout, AbsoluteLayout etc.) or ContentView and then apply some styles or whatever you prefer to this root layout of your CollectionView.
<DataTemplate>
<StackLayout>
<Image
HeightRequest="100"
x:Name="imageCell"
Aspect="AspectFill"
Source="{Binding .}" />
</StackLayout>
</DataTemplate>
Upvotes: 0
Reputation: 7189
I've reproduced a small sample.
Only thing I added was to wrap the image inside a contentview, to apply a padding (which you can ignore)
<CollectionView.ItemsLayout>
<GridItemsLayout Orientation="Vertical" Span="2" />
</CollectionView.ItemsLayout>
<CollectionView.ItemTemplate>
<DataTemplate>
<ContentView Padding="0">
<Image Source="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSzJUY4JZTX9oYsSl1jclFvdsoXhtA0AfxqKkYX2P81Qb3cyX9o"
HeightRequest="150"
Aspect="AspectFill"
/>
</ContentView>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
Upvotes: 0