The result I want to achieve is pretty simple, a list with 2 columns, both with equal width. In Windows Phone 7/8 this could easily be achieved using a ListBox
with a WrapPanel
as ItemsPanel
and setting the ItemWidth
to 240 (as the screen width was 480).
Now I'm Writing a Universal App, but here the problem is that the screen is not guaranted to have a width of 480 (not even for the Phone it seems) so I can't set the ItemWidth
as I want it to fill the width of the screen. I have been able to achieve almost the desired effect using the following XAML
:
<GridView ItemsSource="{Binding Results}" Margin="12">
<GridView.ItemTemplate>
<DataTemplate>
<Grid>
<Image Source="{Binding SampleImage}" />
</Grid>
</DataTemplate>
</GridView.ItemTemplate>
<GridView.ItemsPanel>
<ItemsPanelTemplate>
<WrapGrid MaximumRowsOrColumns="2" Orientation="Horizontal" HorizontalChildrenAlignment="Stretch" VerticalChildrenAlignment="Stretch">
</WrapGrid>
</ItemsPanelTemplate>
</GridView.ItemsPanel>
</GridView>
Which gives the following result:
As seen it successfully gives 2 columns with equal width, BUT the Grid
in the GridView.ItemTemlate
doesn't fill the whole width of each column. I have tried setting HorizontalAlignment="Stretch"
on both that Grid
and on the GridView
itself witout any success. Anyone has any idea of this do this?
My solution is :
<GridView ItemsSource="{Binding Results}" Margin="12"
SizeChanged="GridView_SizeChanged"
x:Name="MyGridView">
<GridView.ItemTemplate>
<DataTemplate>
<Grid>
<Image Source="{Binding SampleImage}" />
</Grid>
</DataTemplate>
</GridView.ItemTemplate>
<GridView.ItemContainerStyle>
<Style TargetType="GridViewItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
<Setter Property="HorizontalAlignment" Value="Stretch"/>
<Setter Property="VerticalContentAlignment" Value="Stretch"/>
<Setter Property="VerticalAlignment" Value="Stretch"/>
</Style>
</GridView.ItemContainerStyle>
</GridView>
Code Behind :
private void GridView_SizeChanged(object sender, SizeChangedEventArgs e)
{
var panel = (ItemsWrapGrid)MyGridView.ItemsPanelRoot;
panel.ItemWidth =panel.ItemHeight= e.NewSize.Width / 2;
}