absqueued
absqueued

Reputation: 3063

How do I iterate through all items in GridView?

This might be the simplest but I am C# beginner so bear with me.

I have a GridView (in XAML), with some data bound. How can I iterate through each item when app loads? I am building Win 8.1 app using XAML/C#.

My GridView:

    <GridView
        ItemsSource="{Binding Source={StaticResource groupedItemsViewSource}}"
        ItemTemplateSelector="{StaticResource MeetingTileSelector}"
        x:Name="itemGridView">
    </GridView>

I wanted to read what each items contains (like image or video, or just a line of texts) and then apply ColSpan, RowSpan, Height accordingly. All I don't know how to iterate through the items.

Upvotes: 2

Views: 4623

Answers (2)

SimonFisher
SimonFisher

Reputation: 410

just try these code, it should work.

        foreach (var item in groupedItemsViewSource)
        {
           var gridViewItem = (FrameworkElement)itemGridView.ContainerFromItem(item);
        }

Best regards!

[EDIT] IMPORTANT: the above code will not work. I just have not realized that groupedItemsViewSource is a CollectionViewSource.

From your code, I guess groupedItemsViewSource is most likely be defined like this:

    <CollectionViewSource x:Key="groupedItemsViewSource"
                          IsSourceGrouped="True"
                          Source="{Binding SomeProperty, Source={StaticResource SomeObject}}"
                          ItemsPath="Items" />

If so, then your can not cast groupedItemsViewSource as CollectionViewSource for iretating purpose.Instead, just iretate Items directly:

        foreach (var item in SomeObject.SomeProperty.Items)
        {
           var gridViewItem = (FrameworkElement)itemGridView.ContainerFromItem(item);

          //here you can do something about the gridViewItem(such like iretating its children)
        }

Upvotes: 2

nestedloop
nestedloop

Reputation: 2646

Try this:

foreach (var item in itemGridView.Items)
{
//do stuff with (each) item
}

given that your grid view is binded to its data source at the moment when you wish to do this iteration.

Check this msdn class reference for more info on the GridView.

If you are looking to change the style of your grid view items, use the

itemGridView.ItemContainerStyle

property of the grid view

Upvotes: 2

Related Questions