You are herePeople > Student Interns > David Itsygin
Register   |  Login
 Tutorial for authoring Silverlight Pivot Applications
Minimize

This tutorial will teach you to make a Silverlight Pivot Page using the Excel Tool with multiple data categories and background colors that are affected by variables.

In order to correctly do the project, we will need to follow these steps:

1. Create a Pivot Collection and generate a .cxml file

2. Set up our IDE and workspace

3. Have the program reference the Pivot Collection

4. Implement a BackgroundColorConverter that will bind background colors to different variables

5. Set up the .xaml file to properly display the data on the PivotViewer panels

6. (Optional) Make images show on the panels

My tutorial will go over these 6 steps in full detail as if you were making the project from scratch, but I will provide finished code from a premade sample to compare your code with a working model. Download the sample code here: (LINK COMING SOON)

 

 

To make a Pivot Collection in Microsoft Excel, you must first download the Excel Tool from here. Once fully installed, there will be a “PivotViewer Collections” tab in the ribbon of Excel. Click “New Collection” to start a spreadsheet. From there, you may delete all columns excluding the “Image Location” column. Though it is not mandatory to have an image for this tutorial (I will demonstrate how to add images later on, but it’s an optional final step), the Pivot Collection Tool currently requires that the “Image Location” column exists. In this tutorial, I’ll be importing 3 sample images included with Windows 7. Make a new column and name the header “Header”. Add at least 3 different variables such as X, Y, and Z. These variables will be used to correlate with trading card background colors in the Pivot Viewer.

 

 Once you are finished with inputting information, you may publish the collection, which we will call “CollectionSample”, and that will generate a .cxml file along with a directory that will contain all image and .xml files.

 

Next, start a new C# Silverlight project in Visual Studio 2010. Make sure you have Visual Studio 2010 SP1 as well as the Silverlight 5 SDK installed beforehand. In this example we’ll name the project “PivotViewerSample”. Navigate to the project directory in Windows Explorer and copy the “CollectionSample.cxml” file as well as the “CollectionSample_files” folder that we made earlier to the root directory of the “PivotViewerSample.Web” folder. This will allow us to reference the .cxml file directly in the code.

 

First of all, you must add a reference to System.Windows.Controls.Pivot. This can be done by right-clicking “References” in your Solution Explorer and then clicking “Add Reference…”. Then, browse for System.Windows.Controls.Pivot in the .NET tab.

 

Now that we have our files set up to work with, open Mainpage.xaml and Mainpage.xaml.cs in the Visual Studio Solution Explorer. In Mainpage.xaml.cs you want your code to look somewhat like this:

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Animation;

using System.Windows.Shapes;

using System.Windows.Controls.Pivot;

using System.Windows.Data;

using System.Windows.Media.Imaging;

using System.Globalization;

 

namespace PivotViewerSample

{

 

 

    public partial class MainPage : UserControl

    {

        public MainPage()

        {

            InitializeComponent();

 

            CxmlCollectionSource source = (CxmlCollectionSource)Resources["CxmlSource"];

            source.UriSource = new Uri(

                new Uri(Application.Current.Host.Source.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped)),

                "CollectionSample.cxml");

        }

 

         private void SourceStateChanged(object sender, CxmlCollectionStateChangedEventArgs args)

        {

            String x = args.ToString();

            try

            {

 

            }

            catch (Exception e)

            {

                x = e.Message;

            }

        }

    }

 

}

 

As you can see, we’ve added a CxmlCollectionSource that references the .cxml file that we made earlier. This will tell the program where to read the data from. Next, add the following code to Mainpage.xaml.cs:

 

        public class BackgroundColorConverter : IValueConverter

        {

            public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)

            {

                return s_brushes[(string)value];

                //return null;

            }

 

            public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)

            {

                throw new NotImplementedException();

            }

 

            private static IDictionary<string, Brush> s_brushes = new Dictionary<string, Brush>()

        {

            { "X", new SolidColorBrush(Colors.Green) },

            { "Y", new SolidColorBrush(Colors.Yellow) },

            { "Z", new SolidColorBrush(Colors.Gray) },

        };

        }

 

Replace “X”, “Y”, and “Z” with the variables that you made in the Excel Collection if you chose to change those. Next we’ll want to edit the Mainpage.xaml file. I will provide the code all at once and then explain the important pieces as we go along. Here is the code that should be in Mainpage.xaml:

 

<UserControl x:Class="PivotViewerExample.MainPage"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

    xmlns:pv="clr-namespace:System.Windows.Controls.Pivot;assembly=System.Windows.Controls.Pivot"

    xmlns:local="clr-namespace:PivotViewerExample"

    mc:Ignorable="d"

    d:DesignHeight="300" d:DesignWidth="400">

    <UserControl.Resources>

        <pv:CxmlCollectionSource x:Key="CxmlSource" StateChanged="SourceStateChanged"/>

        <local:BackgroundColorConverter x:Key="BackgroundColorConverter"/>

    </UserControl.Resources>

    <Grid x:Name="LayoutRoot" Background="White">

        <pv:PivotViewer DataContext="{StaticResource CxmlSource}"

            ItemsSource="{Binding Items}"

            PivotProperties="{Binding ItemProperties}">

            <pv:PivotViewer.ItemTemplates >

                <pv:PivotViewerItemTemplate >

                    <Border BorderBrush="Black" BorderThickness="2" Width="256" Height="256"

                        Background="{Binding [Header][0], Converter={StaticResource BackgroundColorConverter}}">

                        <StackPanel Grid.Column="0"  Orientation="Vertical" HorizontalAlignment="Center" VerticalAlignment="Center">

                            <Grid>

                                <Grid.ColumnDefinitions>

                                    <ColumnDefinition Width="*" >

   </ColumnDefinition>

     </Grid.ColumnDefinitions>

                                <Grid.RowDefinitions>

                                    <RowDefinition Height="Auto"></RowDefinition>

                                    <RowDefinition Height="Auto"></RowDefinition>

                                    <RowDefinition Height="Auto"></RowDefinition>

    </Grid.RowDefinitions>

                            </Grid>

            <TextBlock Grid.Column="0" Grid.Row="1" Text="{Binding [X][0]}" FontSize="38" HorizontalAlignment="Center" TextWrapping="Wrap"/>

                            <StackPanel Orientation="Horizontal" HorizontalAlignment="Center">

                                <TextBlock Text="{Binding [Y][0]}" FontSize="24"/>

                                <TextBlock Text="{Binding [Z][0]}" FontSize="24" Margin="8,0,0,0"/>

                            </StackPanel>

                            <Grid Grid.Column="0" Grid.Row="2" HorizontalAlignment="Center">

                                <Grid.ColumnDefinitions>

                                    <ColumnDefinition Width="*"/>

                                    <ColumnDefinition Width="*"/>

                                </Grid.ColumnDefinitions>

                                <Grid.RowDefinitions>

                                    <RowDefinition Height="Auto"/>

                                    <RowDefinition Height="Auto"/>

                                </Grid.RowDefinitions>

                            </Grid>

                        </StackPanel>

                    </Border>

                </pv:PivotViewerItemTemplate>

            </pv:PivotViewer.ItemTemplates>

         </pv:PivotViewer>

    </Grid>

</UserControl>

 

These lines are very crucial for making the program read the .cxml file that we created earlier:

 

        <pv:PivotViewer DataContext="{StaticResource CxmlSource}"

            ItemsSource="{Binding Items}"

            PivotProperties="{Binding ItemProperties}">

            <pv:PivotViewer.ItemTemplates >

                <pv:PivotViewerItemTemplate >

                    <Border BorderBrush="Black" BorderThickness="2" Width="256" Height="256"

                        Background="{Binding [Header][0], Converter={StaticResource BackgroundColorConverter}}">

 

The 1st line refers to the CxmlSource that was made in the Mainpage.xaml.cs. The 2nd and 3rd line are just general references to what data should be read. And the last line selects the “Header” column header from the Excel document to control the changing of background color according to whether the category is X, Y, or Z as declared in the Mainpage.xaml.cs file. X will make the trading card background green, Y will make it yellow, and Z will make it grey. The next few lines will make sure that the X, Y, and Z will show up as text on the trading card:

 

            <TextBlock Grid.Column="0" Grid.Row="1" Text="{Binding [X][0]}" FontSize="38" HorizontalAlignment="Center" TextWrapping="Wrap"/>

                            <StackPanel Orientation="Horizontal" HorizontalAlignment="Center">

                                <TextBlock Text="{Binding [Y][0]}" FontSize="24"/>

                                <TextBlock Text="{Binding [Z][0]}" FontSize="24" Margin="8,0,0,0"/>

                            </StackPanel>

                            <Grid Grid.Column="0" Grid.Row="2" HorizontalAlignment="Center">

 

Since X is our first line, it will act as the main one and have the largest font. It will also be isolated from the other lines by using a text wrapper.

 

 Lines 3 and 4 show that Y and Z will be on the same line on the trading card as there is no text wrapper between them. Y will be on the left side and Z will be on the right side.  

 

Once you’re ready, compile your project and debug it. It should look somewhat like this except with different content and with a smaller amount of trading cards: 

Working project without images 

 

Once you’ve grasped the concept of how the PivotViewer works, try experimenting with different amounts of columns, background colors, variables, and even using real world data in your Pivot Collection.

 

Making Images Show Up (Optional)

 

To make the images you imported into the Excel Collection appear on the trading cards you want to add this code to your Mainpage.xaml.cs:

 

public class ImageConverter : IValueConverter

    {

        public object Convert(object value,

                              System.Type targetType,

                              object parameter,

                              CultureInfo culture)

        {

            BitmapImage img = new BitmapImage();

 

            if (value != null)

            {

                if (value.ToString() != string.Empty)

                {

                    img.UriSource = new Uri(@"CollectionSample.cxml" + value.ToString(),

                                             UriKind.Absolute);

                }

            }

 

 

            return img;

        }

 

        public object ConvertBack(object value,

                                  System.Type targetType,

                                  object parameter,

                                  CultureInfo culture)

        {

            return null;

        }

    }

 

 

This code is an image converter that will read the images from the collection and organize them appropriately. Next we will want to configure the Mainpage.xaml to display these images correctly. Add this code to the file:

 

<pv:PivotViewerMultiScaleSubImageHost Grid.Column="0" Grid.Row="0" VerticalAlignment="Top"

                                    CollectionSource="{Binding [VisualCollectionSource][0] }" ImageId="{Binding [VisualImageId][0]}"/>

 

 

To work correctly, it must be between <pv:PivotViewerItemTemplate> and </pv:PivotViewerItemTemplate>.

 

Next, we have to change the vertical dimensions of the trading card so that the image wont protrude outside of the borders. To do this, change

<Border BorderBrush="Black" BorderThickness="2" Width="256" Height="256" to

<Border BorderBrush="Black" BorderThickness="2" Width="256" Height="444"

Now, the images should display somewhat like this:

Finalized project complete with images.

 

If there are issues with how the images are displayed, such as them being too big or too small, adjust your panel dimesions until you are happy with the result.