How to bind to a Grouped Items ViewModel with sample data


In MVVM development, you need to define some items collections bindable to your User Interface (View).
First, you must create your collection and items, next, you can create some samples and finally you need to bind these objects to your View (UI).
Since Visual Studio 2013, it’s possible to create your Views and bind data directly in the Visual Editor (without know XAML).

All of that is available for Windows WPF, Windows Phone 8.1, Windows Store Apps, or Windows Universal Apps.

In the following example, I create all classes and XAML code from scratch. This example is a list of contacts grouped by letter’s category.

1. Create the ViewModel

First, we need write all items and collections classes like that.

The following code defines these 3 classes.

using System;
using System.Collections.ObjectModel;
namespace MyApplication.ViewModel
{
    public class ContactsViewModel
    {
        public ContactsViewModel() { this.Groups = new ObservableCollection<ContactsGroupViewModel>(); }
        public ObservableCollection<ContactsGroupViewModel> Groups { get; set; }
    }
    public class ContactsGroupViewModel
    {
        public ContactsGroupViewModel() { this.Items = new ObservableCollection<ContactsItemViewModel>();  }
        public ObservableCollection<ContactsItemViewModel> Items { get; set; }
        public string Letter { get; set; }
    }
    public class ContactsItemViewModel
    {
        public string LastName { get; set; }
        public string FirstName { get; set; }
    }
}

2. Fill the ViewModel with sample data

In the section 3 (below), we’ll use a sample data items to bind with our User Interface… in design mode and/or in runtime mode.

First, create a XAML file with a reference to your ViewModel to easier fill sample items.

<SampleData:ContactsViewModel
          xmlns:SampleData="using:MyApplication.ViewModel" 
          xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
    <SampleData:ContactsViewModel.Groups>
        <SampleData:ContactsGroupViewModel Letter="A">
            <SampleData:ContactsGroupViewModel.Items>
                <SampleData:ContactsItemViewModel LastName="Voituron" FirstName="Denis" />
                <SampleData:ContactsItemViewModel LastName="Dubois" FirstName="Anne" />
            </SampleData:ContactsGroupViewModel.Items>
        </SampleData:ContactsGroupViewModel>
    </SampleData:ContactsViewModel.Groups>
</SampleData:ContactsViewModel>

And create an associated class to load this XAML file in memory.

using System;
namespace MyApplication.SampleData
{
    public class ContactSample : ViewModel.ContactsViewModel
    {
        public ContactSample()
        {
            Uri resourceUri = new Uri("ms-appx:/SampleData/ContactsSample.xaml", UriKind.RelativeOrAbsolute);
            Windows.UI.Xaml.Application.LoadComponent(this, resourceUri);
        }
    }
}

3. Draw your User Interface (View).

a. Create a new Page with a ListView.

Add a new Blank Page (right-click / Add / New Item) and drop a ListView or a GridView in your main screen (from the toolbox).

b. Create a CollectionViewSource in your page.

In your new Page, go in the top of XAML file to add this code (a CollectionViewSource and a DataContext):

<Page … 
    xmlns:sample="using:MyApplication.SampleData" />
<Page.Resources>
    <CollectionViewSource x:Key="ItemsGrouped" IsSourceGrouped="True" ItemsPath="Items" Source="{Binding Groups}"/>
</Page.Resources>
<d:Page.DataContext>
    <sample:ContactSample />
</d:Page.DataContext>

Note that d:Page.DataContext defines a DataContext to our ContactSample data, only in Design Mode. So, in runtime you can fill your ViewModel with real data.

That’s all for coding: all of following steps will be only in visual mode in Visual Studio.

c. Set the ListView.ItemsSource

Switch your interface from XAML to Design mode (menu View / Designer), and select the ListView control.
Press F4 to display the ListView control properties and click on the square next to ItemsSource property, and choose the Create DataBinding command.
Define the Binding type to a StaticResource, select your resource ItemsGrouped and click on OK.

d. Define a look for the HeaderTemplate.

Right-click on the ListView and choose the command Add GroupStyle. So, the command GroupStyle / HeaderTemplate is available.
Before to draw visually your Group Header box, hide this listview 😉 For me, it’s a bug in Visual Studio.

And now, go to edit the current Header Template.

And draw as you want: add a Grid and a TextBlock… and bind the
TextBlock.Text property to the Letter property of your SampleData.Groups collection item.

e. Define a look for the ItemTemplate.

Right-click on the ListView and choose the command Edit ItemTemplate / Create Empty. And choose a name for this ItemTemplate (ex. ContactItemTemplate).

And draw as you want (a Grid, 2 TextBlock)… and bind the TextBox.Text to LastName and FirstName of a contact item.

That’s all… you can unhide the ListView or run this application to display a contact list grouped by letter. Of course, in runtime, you need select correct data (not sample from xaml) and sort all contacts by first letter.

Advertisements
Tagged with: , ,
Posted in Formation, MVVM
One comment on “How to bind to a Grouped Items ViewModel with sample data
  1. w3bbodavid says:

    IsSourceGrouped is not available in WPF, only UWP XAML.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow me
   RSS Feed    Twitter    Linked In

Write you email address to subscribe at this blog and to receive new posts by mail.

Join 611 other followers

Who I am?






%d bloggers like this: