问题
I'm building a universal app and my Win8.1 app has to show a grid of items. Normally the grid consists of 3 columns, but on smaller screens I want the items to wrap so that there are only 2 columns (or even 1). This is my code:
<GridView ItemsSource="{Binding Regions}" IsItemClickEnabled="True">
<GridView.ItemsPanel>
<ItemsPanelTemplate>
<ItemsWrapGrid Orientation="Horizontal" MaximumRowsOrColumns="3" MinWidth="400" />
</ItemsPanelTemplate>
</GridView.ItemsPanel>
<GridView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Margin="10">
<Image Source="{Binding Code, Converter={StaticResource FlagIconConverter}, ConverterParameter='/Assets/Icons/Flags/{0}.png'}" Width="30" />
<TextBlock Text="{Binding NativeName}" Style="{StaticResource BodyTextBlockStyle}" Margin="10,0,0,10" VerticalAlignment="Center" />
</StackPanel>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
Whenever I make the app smaller, the items do not automatically wrap. I tried solving this by changing the MaximumRowsOrColumns
property with a VisualStateManager
but that didn't work because it couldn't access my WrapGrid
for some reason. Changing the property from code-behind didn't work either, because again it couldn't access the WrapGrid.
I tried this with both WrapGrid
and ItemsWrapGrid
(what is the difference anyway?) and ListView
and GridView
. No difference there.
Does anyone know how to accomplish this?
回答1:
You shouldn't need to do anything. It should wrap based on the available client area. The only thing I can think of that would not make it wrap is that you put your <GridView>
inside a fixed width container or a container that is size Auto
in which you don't update the Observable Collection to notify the Grid to redraw/update itself.
For example this will not wrap.
<Grid Width="1000">
<GridView x:Name="myGridView" IsItemClickEnabled="True">
<GridView.ItemsPanel>
<ItemsPanelTemplate>
<ItemsWrapGrid Orientation="Horizontal" MaximumRowsOrColumns="5"/>
</ItemsPanelTemplate>
</GridView.ItemsPanel>
<GridView.ItemTemplate>
<!-- DATATEMPLATE -->
</GridView.ItemTemplate>
</GridView>
</Grid>
However get rid of that Width=1000
and it will wrap.
Example output 3 different sizes
来源:https://stackoverflow.com/questions/25953070/windows-8-1-how-to-automatically-wrap-grid-items