Dynamic Data Binding to a Pivot Header Table Windows phone 8.1

Over the last few months, I have been working on understanding XAML better and how the various controls handle data binding. One of my biggest headaches was trying to understand design-time binding. This is not as obvious as one might think and quite honestly, I don’t think it even always works properly. I discussed how to accomplish design-time binding in detail using a XAML file for the mock data here.

Today, I am going to talk about dynamic binding with the pivot table controls. There was very little on the web that would go step by step in explaining the process and where the ItemSources/DataContext needs to be defined. I found a great example here. In this example, he is using some simple mock data to bind to the header and pivot item lists. The biggest issue I was having problems with the Pivot header that is scrolled through when there are more than one Pivot. An example of the header I am referring to is shown below (first and second).

image

The example most likely will look familiar if you have created a Pivot table before because it is the default template when you use VS 2012-2013. The biggest problem I found was that most of the example show how to bind to the PivotItems, but not the Pivot Header itself. There is alos a PivotItem header as well. It’s not like it is confusing enough. Lets add a bunch of extra confusion. The interesting thing is that tutorial after tutorial talks all about the need for data binding and dynamic changes on the View that seperates the View from the Models so that they don’t know anything about each other. Well how is the header any different? If you have dynamic items, don’t you want the lists to also be dynamic? Anyway, I digress.

Solution

So enough soapbox talk, lets get to some coding examples. First thing you want to do is create a new Windows Phone project using the Windows Phone Pivot Template.

Creating the Project

image

Once the project loads, the first thing you want to do is create the following classes in the DataModel folder (this will be important later):

Building the Models

PersonModel

image

Now Create a Classroom class that has a list of persons attending the class.

image

The final class will act as our repository that loads our fake data. We will call it the DataLoader.

image

Now in the PivotPage.xaml.cs file that acts as the code behind for the main Pivot page. There is a method called the NavigationHelper_LoadState. This method is called whenever the page is about to load. This is helpful to load data right before the page is brought into view so it can bind the data to the views controls. (we are going to be using this method to load our data).

Assign the data to the DataContext

A DataContext is the object that binds the data you provide with the Views data bindings. If this is not clear, it will be momentarily.

Add these two lines to the NavigationHelper_LoadState method:

image

The first line create an instance of you DataLoader. Because we called the LoadData method in the constructor, the data is preloaded into the Classroom and Person objects. Therefore you don’t need to call dataLoader.LoadData(). The second line assigns a key of Classrooms that will be referenced in the XAML binding. The object assigned to this DataContext is the list of Classrooms which in turn contains a list of Persons. This will be accessible to the data binders at runtime.

How DataContext is doing its Magic

Before moving on, I thought I’d explain why the DataContext and how it works. If you didn’t already know, the PivotPage.xaml and the PivotPage.xaml.cs are bound together via .NET, so they both intimately aware of each other. This is part of what data binding is used for. It decouples the logic and DataModel from the View (XAML). This makes it easier to make a change to the model without directly affecting the View itself. The DataContext is used to bind to list type controls (like ListView and Pivot tables) in the view by it’s provided lists and underlining properties. In our case, there is a DefaultViewModel observable dictionary that the Pivot project template provides and wires up to the DataContext at the top of the XAML page like this.

image

  With that all said, lets start the binding part.

Binding to the View

 <Grid>
        <Pivot x:Uid="Pivot" Title="MY APPLICATION" 
               ItemsSource="{Binding Classrooms}"
               x:Name="pivot" CommonNavigationTransitionInfo.IsStaggerElement="True">
            <!--Pivot item one-->
            <Pivot.TitleTemplate>
                <DataTemplate>
                    <StackPanel  Orientation="Horizontal" Height="65">
                        <Image Height="50" Width="50"  Source="ms-appx:///Assets/shopping-trolley-no-bg.png"/>
                        <TextBlock x:Name="Title" Text="Lists" Height="25" FontSize="18" Margin="5"  FontWeight="Bold"/>
                    </StackPanel>
                </DataTemplate>
            </Pivot.TitleTemplate>
            <Pivot.HeaderTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Header}"></TextBlock>
                </DataTemplate>
            </Pivot.HeaderTemplate>
            <Pivot.ItemTemplate>
                <DataTemplate>
                    <ListView
                    ItemsSource="{Binding Persons}"
                    IsItemClickEnabled="True"
                    ItemClick="ItemView_ItemClick"
                    ContinuumNavigationTransitionInfo.ExitElementContainer="True" FontSize="12" Foreground="#FFF0CCA7" FontStyle="Italic">
                        <ListView.ItemTemplate>
                            <DataTemplate>
                                <StackPanel Orientation="Horizontal">
                                    <TextBlock x:Name="AddShoppingItem" 
                                            Text="{Binding FirstName}"
                                            Style="{StaticResource ListViewItemContentTextBlockStyle}"
                                            Pivot.SlideInAnimationGroup="1" 
                                            CommonNavigationTransitionInfo.IsStaggerElement="True"/>

                                    <TextBlock
                                    Text="{Binding LastName}"
                                    TextWrapping="WrapWholeWords"
                                    Pivot.SlideInAnimationGroup="2" 
                                    CommonNavigationTransitionInfo.IsStaggerElement="True" 
                                    Style="{ThemeResource ListViewItemContentTextBlockStyle}"
                                    Margin="22,0,19,0"/>
                                </StackPanel>
                            </DataTemplate>
                        </ListView.ItemTemplate>

                    </ListView>

                </DataTemplate>
            </Pivot.ItemTemplate>
        </Pivot>
    </Grid>

 

This snippet couldn’t fit in a screenshot, so I put it into a snippet plugin. Lets break this down into parts.

Templates

Let me start by explaining a template. A template is something that is designed to provide a developer the ability to customize how a particular control is displayed. To do this, you add a control and within that control define Template using the syntax Control.TypeOfTemplate. Unfortunately, a template property can be named differently on each control type. It all depends on what the control is trying to accomplish. Here is how we designed the Pivot top level control (Header and title, not the items yet).

image

 

As you can see in the image, we define both a Title template and a header template using the syntax Pivot.TitleTemplate and Pivot.HeaderTemplate respectively. One thing that never changes is that inside the template property, you need to add a <DataTemplate> tag. This tag belongs inside the controls template property prior to ANY other controls. If you try to add a control out right, such as a TextBox, you will get errors and the view will not build. The DataTemplate encapsulates the controls that will bind your data and display it how you want it to.

Binding the controls is like you would anything else inside the Grid. You can add StackPanels, TextBoxes etc..

Binding the List to the Pivot Control

The image below shows us binding the Classrooms object to the Pivot Control itself using the ItemsSource property. We defined the name Classrooms when we assigned the list of Classrooms to the DefaultViewModel. The DefaultViewModel was then assigned to the DataContext.

image

Once the Classroom list has been bound to the top level Pivot, we can bind the various templates as shown above. because the Header was the main reason for this post, here is an example of binding the Header Template with a

image

I hope this helped someone and I will be posting this on my CodePlex account here

 

Happy Coding Smile

Advertisements

About Gregg Coleman

I am Senior-level Software Engineer working primarily these days with .NET. I have a good working knowledge of ASP.NET MVC, Web Forms, WCF web services and Windows Services. I spend much of my time in the Web Services (SOAP and REST) world in my current job designing and implementing various SOA architectures. I have been in the software engineering industry for about 6 years now and will not now nor ever consider myself an "expert" in programming because there is always so much to learn. My favorite thing about designing software is there are always new emerging technologies and something to learn every day! My current job has me spending much of my job on the bleeding edge of technologies and changing gears all the time, so I'm never bored and always challenged. On my spare time I enjoy weight training, reading and venturing to new places near by. Of course programing and learning new technologies are another hobby of mine.
This entry was posted in .NET, C#, Computer Technology, Data Binding, DataAnnotation, Design Binding, Generics, MVVM, Partial Classes, Windows Phone, Windows Store Apps and tagged , , , , , , , . Bookmark the permalink.

One Response to Dynamic Data Binding to a Pivot Header Table Windows phone 8.1

  1. Pingback: Traversing the Visual tree in Windows Phone 8.1 using VisualTreeHelper | Object Reference Hell

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s