问题
I have created a GridView which gets data through data binding. What I want to do next is make the GridView item width dynamic according to the Screen Size (Like the ones they have done in the Windows 10 news, sports app, etc.) So far I have done it successfully for minimum window width 0 using visual state manager by setting the horizontal alignment to stretch, but I am not being able to continue this for other wider window sizes.
Any kind of help for sorting this out will be appreciated.
回答1:
If you want the items to stretch to fill the horizontal space and be able to specify how many items per row you want, then you'll have to set the ItemWidth of the ItemsWrapGrid manually within the GridView's SizeChanged event.
Here's an example:
<GridView x:Name="gridView" SizeChanged="onGridViewSizeChanged">
<GridView.ItemTemplate>
<DataTemplate>
<Grid Background="GreenYellow" BorderBrush="Black" BorderThickness="2">
<TextBlock Text="{Binding}" HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="40"/>
</Grid>
</DataTemplate>
</GridView.ItemTemplate>
<GridView.ItemContainerStyle>
<Style TargetType="GridViewItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
<Setter Property="VerticalContentAlignment" Value="Stretch"/>
<Setter Property="Margin" Value="0"/>
</Style>
</GridView.ItemContainerStyle>
<GridView.ItemsPanel>
<ItemsPanelTemplate>
<ItemsWrapGrid Orientation="Horizontal"/>
</ItemsPanelTemplate>
</GridView.ItemsPanel>
<x:String>1</x:String>
<x:String>2</x:String>
<x:String>3</x:String>
<x:String>4</x:String>
<x:String>5</x:String>
<x:String>6</x:String>
<x:String>7</x:String>
<x:String>8</x:String>
</GridView>
private void onGridViewSizeChanged(object sender, SizeChangedEventArgs e)
{
// Here I'm calculating the number of columns I want based on
// the width of the page
var columns = Math.Ceiling(ActualWidth / 300);
((ItemsWrapGrid)gridView.ItemsPanelRoot).ItemWidth = e.NewSize.Width / columns;
}
You could probably bundle this into a Behavior or attached property too.
来源:https://stackoverflow.com/questions/41139535/gridview-item-dynamic-width-according-to-screen-size-in-uwp