Hello,
After testing, in .net7, both DeviceDisplay.Current.MainDisplayInfo.Width
and DeviceDisplay.Current.MainDisplayInfo.Density
have values of 0, which results in a constant result of width to NaN infinity.
This causes if (width > 3800)
to always be true.
This issue was fixed in .Net 8.
Please refer to DeviceDisplay.Current.MainDisplayInfo not available on windows #6976 for more details.
Update: After testing, there are no issues with this feature design. You need to configure the ItemTemplate in the xaml page of the CollectionView for this layout to appear. Please refer to the following code:
// If you don't define the style of the ItemTemplate, the custom layout can't be displayed.
<CollectionView x:Name="collectionview"
ItemsSource="{Binding Monkeys}"
SelectionMode="Multiple"
SelectionChanged="OnCollectionViewSelectionChanged">
<CollectionView.ItemTemplate>
<DataTemplate>
<Grid Padding="10">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Label Grid.Column="1"
Text="{Binding Name}"
FontAttributes="Bold" />
<Label Grid.Row="1"
Grid.Column="1"
Text="{Binding Location}"
FontAttributes="Italic"
VerticalOptions="End" />
</Grid>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
//in c#
void ChangeSpanByDeviceWidth() {
var width = DeviceDisplay.Current.MainDisplayInfo.Width / DeviceDisplay.Current.MainDisplayInfo.Density;
GridItemsLayout gridItemsLayout = new GridItemsLayout(ItemsLayoutOrientation.Vertical);
gridItemsLayout.HorizontalItemSpacing = 5;
gridItemsLayout.VerticalItemSpacing = 5;
if(width > 3800)
{
gridItemsLayout.Span = 10;
}else if(width > 2500)
{
gridItemsLayout.Span = 8;
}else if(width > 1200)
{
gridItemsLayout.Span = 6;
}else if(width > 1000)
{
gridItemsLayout.Span = 4;
}
else
{
gridItemsLayout.Span = 3;
}
collectionview.ItemsLayout = gridItemsLayout;
}
After testing, the application could display different numbers of elements according to the width as expected.
Best Regards,
Alec Liu.
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.