WinRT app guide: Step 7: Using CollectionViewSource in WinRT
To read the other steps in the step by step guide for creating a Metr/ WInRT application go here
Welcome back! As promised we will be working more on the presentation of data today! I’m not sure if you noticed, but the items in the list were not grouped, and we would of course love to have them grouped by category, it makes more sense that way. And we would also love to have the list sorted by Titles and Category. We will do the grouping by using CollectionViewSource and IGrouping, and if you have used CollectionViewSource before I will have to warn you that we are a bit more limited in the XAML in WinRT,- and that it is done differently here. This is how it can be done:
The end result, after using CollectionViewSource in WinRT
Add a CollectionViewSource to the Page resources, give it a name and set IsSourceGrouped to true. Yes the source will be grouped once it gets it.
[sourcecode language=“XML”]
<Page.Resources>
</Page.Resources>
[/sourcecode]
Now we set the Listview ItemsSource to the resource, and we add a Listview.GroupStyle and declare a header template inside of it, bind the title of this header to the Key. Notice that we are binding the width of the element inside the datatemplate to a column, this is so it will stretch and fill up the whole space. To do this we must assign an x:name to the column we are binding against.
[sourcecode language=“XML”]
<Grid.ColumnDefinitions>
</Grid.ColumnDefinitions>
<ListView Background="Olive" x:Name="itemListView" ItemsSource="{Binding Source={StaticResource activitiesCollection}}" >
<ListView.GroupStyle>
<GroupStyle.HeaderTemplate>
<TextBlock Text=’{Binding Key}’ Foreground="White" Margin="5" FontSize="22" FontFamily="Segoe UI Light" />
</GroupStyle.HeaderTemplate>
[/sourcecode]
We are not done! We need to sort and group our items, so let’s add a new method in the repository:
[sourcecode language=“csharp”]
public IEnumerable<IGrouping<string, StudyActivity» GetAllGrouped()
{
return _studyActivities.OrderBy(x => x.Title).GroupBy(x => x.CategoryName);
}
[/sourcecode]
And finally we need to create an instance of the items (grouped and sorted) and add it to our CollectionViewSource. We’ll do this by changing the SetListViewSource to SetCollectionViewSource and setting the collection source instead of the ListView itemsSource.
[sourcecode language=“csharp”]
void SetCollectionViewSource()
{
activityCollection.Source = new StudyActivityRepository(CreateActivities()).GetAllGrouped();
}
[/sourcecode]
Hit F5 and have a look at our beautiful app!
Next blogpost we’ll have a look at design briefly and talk about some of the design requirements, and start implementing them.
Comments
Hi, Can you show how to use filter with ObservableCollection (applying to WinRT), if we need, for example, show only specific elements in the ListView or GridView and hide others? Thanks advance. regards, Maks
Last modified on 2012-09-10