How to add Items to GridView in C# Windows Store App (Win8)

Posted by flexage on Stack Overflow See other posts from Stack Overflow or by flexage
Published on 2012-11-12T02:42:57Z Indexed on 2012/11/12 5:00 UTC
Read the original article Hit count: 166

To keep things simple let's just say I have a c# Windows Store Project for Windows 8 that has the following items:

  • GridView (PlatformsGrid)
  • List«PlatformSearchResult» (allPlatforms)
  • DataTemplate (PlatformDataTemplate) in standardstyles.xaml

allPlatforms is a collection of "PlatformSearchResult"objects populated from an online API, and has the following 3 properties:

  1. ID
  2. Name
  3. Alias

I am able to add a new item to the gridview for each object that exists in my allPlatforms collection, however the items are blank and do not show the data from my objects.

A quick summary of the current code looks like this:

XAML Markup:

<!-- Platforms Content -->
<GridView x:Name="PlatformsGrid" Grid.Row="1"
  CanReorderItems="True" CanDragItems="True" 
  ItemTemplate="{StaticResource PlatformDataTemplate}" >
    <GridView.ItemsPanel>
        <ItemsPanelTemplate>
            <WrapGrid MaximumRowsOrColumns="2" 
              VerticalChildrenAlignment="Top" HorizontalChildrenAlignment="Center" />
        </ItemsPanelTemplate>
    </GridView.ItemsPanel>
</GridView>

Data Template

<!-- Platform Item Template -->
<DataTemplate x:Key="PlatformDataTemplate">
    <Grid Background="#FF939598" Height="250" Width="250">
        <Image Source="/SampleImage.png"  Stretch="UniformToFill"/>
        <StackPanel Orientation="Vertical" Background="#CC000000" 
                Height="90" VerticalAlignment="Bottom">
            <TextBlock Text="{Binding Name}" 
                   Margin="10,3,0,0" Width="242" Height="62" 
                   TextTrimming="WordEllipsis" TextWrapping="Wrap" HorizontalAlignment="Left"/>
            <TextBlock Text="{Binding Alias}" 
                   Margin="10,2,0,0" Width="186" Height="14" 
                   TextTrimming="WordEllipsis" HorizontalAlignment="Left" FontSize="9" Opacity="0.49"/>
        </StackPanel>
    </Grid>
</DataTemplate>

Controlling Function

    private async void FetchItemInfo_Loaded(object sender, RoutedEventArgs e)
    {
        // Get List of Top Games
        List<PlatformSearchResult> allPlatforms = new List<PlatformSearchResult>();
        allPlatforms = await GamesDB.GetPlatforms();

        // Dynamically Create Platform Tiles
        foreach (PlatformSearchResult platform in allPlatforms)
        {
            PlatformsGrid.DataContext = platform;
            PlatformsGrid.Items.Add(platform);
        }
    }

How do I get the added items to show the appropriate object properties (ignoring the image for now), I'm just interested in populating the content of the TextBlocks.

I appreciate any help anyone can provide!

Thanks, Alex.

© Stack Overflow or respective owner

Related posts about c#

Related posts about xaml