Docstoc

Windows Phone Toolkit Aug 2011 in depth-v1

Document Sample
Windows Phone Toolkit Aug 2011 in depth-v1 Powered By Docstoc
					Silverlight for Windows Phone Toolkit in Depth




Silverlight for Windows
Phone Toolkit

  In Depth

by Boryana Miloshevska




www.windowsphonegeek.com
                                                 2
Silverlight for Windows Phone Toolkit in Depth




About the Author
Boryana Miloshevska is a software developer with more than 6 years of professional experience with
.NET technologies. She is a co-founder of www.windowsphonegeek.com - one of the biggest windows
phone development communities. She is also working as a consultant in the areas of Silverlight and
Windows Phone application development.

What else?

   -   Active blogger and tech enthusiast trying to contribute to the windows phone development
       community in various ways. Author of more than 300 development articles, tutorials and guides
       related to Silverlight and Windows Phone 7 technology most of which published on
       www.windowsphonegeek.com .
   -   MCTS, MCPD Web and Desktop development
   -   Winner of the Microsoft “Engineering Excellence Achievement” Award
   -   MSc Computer Science
   -   MSc Technology Entrepreneurship (UCL , London UK)




www.windowsphonegeek.com
                                                                                                       3
Silverlight for Windows Phone Toolkit in Depth




Table of Contents
About the Author .................................................................................................................. 3
Introduction ........................................................................................................................ 10
   Who is this book for? .............................................................................................................................. 10
   What this book covers? .......................................................................................................................... 10
   How is this book structured? .................................................................................................................. 11
   Source code............................................................................................................................................. 12
   What else? .............................................................................................................................................. 12
   Why did I decide to write this FREE e-book? .......................................................................................... 12
Introduction to Silverlight for Windows Phone .................................................................... 14
Introduction to Silverlight for Windows Phone Toolkit ......................................................... 17
   Components included in the Silverlight for Windows Phone Toolkit ..................................................... 17
   What's included in the source code? ...................................................................................................... 18
   Suggestions? Features? Questions? ....................................................................................................... 18
   Official Blogs & Tweets ........................................................................................................................... 19
   What else will you need? ........................................................................................................................ 19
   Getting Started with the Silverlight for Windows Phone Toolkit ........................................................... 20
   Option1: Install the Windows Phone Toolkit .msi .................................................................................. 21
   Option2: Download the “Silverlight for Windows Phone Toolkit Source & Sample - Aug 2011.zip” ..... 24
   Option3: Download only the XAP file ..................................................................................................... 26
   Option4: Install Windows Phone Toolkit using NuGet ........................................................................... 26
   How to use unofficial builds.................................................................................................................... 27
   How to use Windows Phone Toolkit in Visual Studio ............................................................................. 30
   How to add Windows Phone Toolkit Controls to the Visual Studio Toolbox ......................................... 33
   How to use Windows Phone Toolkit in Expression Blend ...................................................................... 38
AutoCompleteBox ............................................................................................................... 42
   Overview ................................................................................................................................................. 42
   Getting Started........................................................................................................................................ 42
   Key Properties ......................................................................................................................................... 44


www.windowsphonegeek.com
                                                                                                                                                                   4
Silverlight for Windows Phone Toolkit in Depth



   Key Events ............................................................................................................................................... 50
   Key Methods ........................................................................................................................................... 52
   Data Binding AutoCompleteBox ............................................................................................................. 53
   Data Binding AutoCompleteBox via ValueMemberBinding.................................................................... 57
ContextMenu ...................................................................................................................... 59
   Overview ................................................................................................................................................. 59
   Getting Started........................................................................................................................................ 59
   Key Properties ......................................................................................................................................... 60
   Key Events ............................................................................................................................................... 62
   MenuItem ............................................................................................................................................... 63
   MenuItem Key Properties ....................................................................................................................... 63
   MenuItem Key Events ............................................................................................................................. 64
   Populating ContextMenu with MenuItems ............................................................................................ 64
   Data Binding ContextMenu..................................................................................................................... 66
   Using ContextMenu inside ListBox ItemTemplate (DataTemplate) ....................................................... 67
DatePicker........................................................................................................................... 71
   Overview ................................................................................................................................................. 71
   Getting Started........................................................................................................................................ 71
   Key Properties ......................................................................................................................................... 73
   Key Events ............................................................................................................................................... 74
   Customizing the full-screen picker page ................................................................................................. 75
ExpanderView ..................................................................................................................... 78
   Overview ................................................................................................................................................. 78
   Getting Started........................................................................................................................................ 78
   Key Properties ......................................................................................................................................... 79
   Key Events ............................................................................................................................................... 81
   Data Binding ExpanderView.................................................................................................................... 82
   ExpandAll and CollapseAll Example ........................................................................................................ 88
GestureService and GestureListener .................................................................................... 89
   Overview ................................................................................................................................................. 89



www.windowsphonegeek.com
                                                                                                                                                                   5
Silverlight for Windows Phone Toolkit in Depth



   What is GestureService? ......................................................................................................................... 90
   What is GestureListener?........................................................................................................................ 91
   Getting Started........................................................................................................................................ 91
   GestureListener Key Events .................................................................................................................... 93
   Examples ................................................................................................................................................. 99
HubTile ............................................................................................................................. 101
   Overview ............................................................................................................................................... 101
   Getting Started...................................................................................................................................... 101
   Key Properties ....................................................................................................................................... 103
   HubTileService ...................................................................................................................................... 104
   Data Binding HubTile ............................................................................................................................ 106
   Freezing and Unfreezing tiles................................................................................................................ 109
ListPicker ........................................................................................................................... 112
   Overview ............................................................................................................................................... 112
   Getting Started...................................................................................................................................... 112
   Key Properties ....................................................................................................................................... 114
   Key Events & Methods .......................................................................................................................... 117
   Data Binding ListPicker.......................................................................................................................... 117
   Working with ListPicker SelectedItem .................................................................................................. 120
LockablePivot .................................................................................................................... 125
   Overview ............................................................................................................................................... 125
   Getting Started...................................................................................................................................... 125
   Key Properties ....................................................................................................................................... 126
   Example ................................................................................................................................................. 126
LoopingSelector................................................................................................................. 130
   Overview ............................................................................................................................................... 130
   Getting Started...................................................................................................................................... 130
   Key Properties ....................................................................................................................................... 136
   Key Events ............................................................................................................................................. 136
   ILoopingSelectorDataSource ................................................................................................................. 137



www.windowsphonegeek.com
                                                                                                                                                                   6
Silverlight for Windows Phone Toolkit in Depth



   Implementing a generic LoopingSelectorDataSource .......................................................................... 137
   LoopingSelector with Double Data ....................................................................................................... 141
   LoopingSelector with Int Data .............................................................................................................. 142
   LoopingSelector with String Data ......................................................................................................... 143
   LoopingSelector with DateTime Data ................................................................................................... 144
   Advanced Data Binding using IComparable<T> .................................................................................... 145
   Advanced Data Binding using a separate Comparer............................................................................. 148
LongListSelector ................................................................................................................ 151
   Overview ............................................................................................................................................... 151
   Visual structure ..................................................................................................................................... 151
   Getting Started...................................................................................................................................... 153
   Key Properties ....................................................................................................................................... 154
   Key Events ............................................................................................................................................. 159
   Key Methods ......................................................................................................................................... 162
   Data Binding LongListSelector .............................................................................................................. 163
   Customizing LongListSelector group popup ......................................................................................... 170
   Animating LongListSelector group items using transitions................................................................... 171
   Dynamically Insert, Update and Delete data in a data bound LongListSelector .................................. 175
MultiselectList ................................................................................................................... 181
   Overview ............................................................................................................................................... 181
   Getting Started...................................................................................................................................... 181
   Key Properties ....................................................................................................................................... 182
   Key Events ............................................................................................................................................. 183
   MultiselectItem ..................................................................................................................................... 184
   MultiselectItem Key Properties & Events ............................................................................................. 184
   Data Binding MultiselectList ................................................................................................................. 185
PhoneTextBox ................................................................................................................... 193
   Overview ............................................................................................................................................... 193
   Getting Started...................................................................................................................................... 193
   Key Properties ....................................................................................................................................... 194




www.windowsphonegeek.com
                                                                                                                                                                  7
Silverlight for Windows Phone Toolkit in Depth



   Key Events ............................................................................................................................................. 197
PerformanceProgressBar ................................................................................................... 198
   Overview ............................................................................................................................................... 198
   Getting Started...................................................................................................................................... 199
   Key Properties ....................................................................................................................................... 200
Transitions ........................................................................................................................ 201
   Overview ............................................................................................................................................... 201
   Key concepts ......................................................................................................................................... 201
   Getting Started...................................................................................................................................... 204
   Page Transition ..................................................................................................................................... 206
   UIElement Transition ............................................................................................................................ 207
   Custom Transitions ............................................................................................................................... 208
TiltEffect............................................................................................................................ 215
   Overview ............................................................................................................................................... 215
   Getting Started...................................................................................................................................... 215
   Key Properties ....................................................................................................................................... 217
   How to Enable TiltEffect globally .......................................................................................................... 217
   How to Suppress TiltEffect .................................................................................................................... 218
   Adding more controls to TiltableItems ................................................................................................. 219
   Adding TiltEffect to data bound ListPicker Items.................................................................................. 219
TimePicker ........................................................................................................................ 221
   Overview ............................................................................................................................................... 221
   Getting Started...................................................................................................................................... 221
   Key Properties ....................................................................................................................................... 223
   Key Events ............................................................................................................................................. 225
   Customizing the full-screen picker page ............................................................................................... 225
ToggleSwitch ..................................................................................................................... 228
   Overview ............................................................................................................................................... 228
   Getting Started...................................................................................................................................... 228
   Key Properties ....................................................................................................................................... 229



www.windowsphonegeek.com
                                                                                                                                                                  8
Silverlight for Windows Phone Toolkit in Depth



   Key Events ............................................................................................................................................. 231
   Dynamically Changing ToggleSwitch Content depending on the current State ................................... 232
WrapPanel ........................................................................................................................ 234
   Overview ............................................................................................................................................... 234
   Getting Started...................................................................................................................................... 234
   Key Properties ....................................................................................................................................... 236
   Horizontal WrapPanel ........................................................................................................................... 236
   Vertical WrapPanel ............................................................................................................................... 237
   WrapPanel as ItemsPanel ..................................................................................................................... 237
Additional Components ..................................................................................................... 239
   RecurringDaysPicker ............................................................................................................................. 239
   HeaderedItemsControl ......................................................................................................................... 240
   DateTimeConverters ............................................................................................................................. 240
   LocalizedResources ............................................................................................................................... 244




www.windowsphonegeek.com
                                                                                                                                                                  9
Silverlight for Windows Phone Toolkit in Depth




Introduction
Who is this book for?
The target audience of this book is anyone who is interested in Silverlight for Windows Phone
development. It covers all controls from the Microsoft Silverlight for Windows Phone Toolkit 7.1
- Aug 2011 SDK (Mango).

This book contains all the information necessary to get you started with the Silverlight for
Windows Phone Toolkit. It is suitable for both beginners and advanced developers.

Before you begin you will need to have a basic understanding of:

       Silverlight principles
       Windows Phone principles
       C# programming

What this book covers?
The book covers “in depth” all controls from the Microsoft Silverlight for Windows Phone
Toolkit including:

    o   AutoCompleteBox
    o   ContextMenu
    o   DatePicker
    o   DateTimeConverters
    o   ExpanderView
    o   Gestures
    o   HeaderedItemsControl
    o   HubTile
    o   ListPicker
    o   LocalizedResources
    o   LockablePivot
    o   LoopingSelector
    o   LongListSelector
    o   MultiselectList
    o   Page Transitions
    o   PerformanceProgressbar
    o   PhoneTextBox
    o   WrapPanel


www.windowsphonegeek.com
                                                                                                   10
Silverlight for Windows Phone Toolkit in Depth




    o   TiltEffect
    o   TimePicker
    o   ToggleSwitch

Furthermore the first two chapters make a quick introduction to the main concepts related to
Silverlight and Windows Phone application development and how to get started using external
libraries like the “Silverlight for Windows Phone Toolkit”.

How is this book structured?
In this book you will learn how to use the different controls that the “Silverlight for Windows
Phone Toolkit” offers.

Chapter1 is a brief introduction to the main Silverlight and Windows Phone concepts. You will
learn the key concepts that you need to know in order to get started with Windows Phone
application development.

Chapter2 is focused on getting started with the “Silverlight for Windows Phone Toolkit”. It gives
you all the necessary information from start to finish including:

       What is in the toolkit?
       System requirements
       Installing
       Windows Phone Toolkit and Visual Studio
       Visual Studio Toolbox integration
       Expression Blend integration
       Unofficial builds
       Issue Tracker

In Chapters 3 through Chapter 22 you will learn how to use each one of the toolkit`s controls
“in depth”. Each chapter contains the following main sections:

“Overview”: a brief description of the main features

“Getting Started”: explains how to get started using the control in XAML and C#

“Key Properties”/ “Key Methods”/ “Key Events”: a full explanation of the available public API
(with short samples)

Examples: Depending on the importance and how complex the control is there are more or
less examples with source code and detailed explanation.


www.windowsphonegeek.com
                                                                                                    11
Silverlight for Windows Phone Toolkit in Depth




Source code
The full source code mentioned in this book can downloaded from here:
http://www.windowsphonegeek.com/WPToolkitBook

All sample projects from this book target Windows Phone 7.1 (Mango).

The following conventions are used regarding the source code (XAML and C#):

XAML
//XAML code here



C#
//C# code here



             NOTE: Important things here!




What else?
Half of this book is based on the “21 WP7 Toolkit in Depth articles covering all controls” series
of articles that I wrote and published on WindowsPhoneGeek.com a while ago:
http://www.windowsphonegeek.com/articles/21-WP7-Toolkit-in-Depth-articles-covering-all-controls

However, I have added some new chapters that are not published anywhere else and a lot of
new examples, explanations, etc.

Why did I decide to write this FREE e-book?
Here are my points why I decided to write this book for FREE:

Point1. First of all, because “Silverlight for Windows Phone Toolkit” is a FREE library with great
controls, provided by Microsoft.

Point2. There is a lot of paid content on the web regarding Windows Phone development and
quite a few FREE one. This was the reason why I founded www.windowsphonegeek.com about
a year ago: to create a FREE community with high quality and up to date windows phone



www.windowsphonegeek.com
                                                                                                     12
Silverlight for Windows Phone Toolkit in Depth




development content. So having in mind that there is no documentation for the toolkit or any
books available, I decided to write and share a FREE one.




www.windowsphonegeek.com
                                                                                               13
Silverlight for Windows Phone Toolkit in Depth




Introduction to Silverlight for Windows
Phone
The Windows Phone Application Platform enables developers to create engaging consumer
experiences running on a Windows® Phone. It is built upon existing Microsoft® tools and
technologies such as Visual Studio, Expression Blend®, Silverlight®, and the XNA Framework.
Developers already familiar with those technologies and their related tools will be able to
create new applications for Windows Phone without a steep learning curve.

The Windows Phone Application Platform offers large set of tools, a cohesive and well designed
managed API set, runtime services on devices that can be used to access web services in the
cloud such as Xbox LIVE®, Windows Azure, location, and notification services. It also offers
developers a Windows Phone Marketplace to distribute their applications.




Silverlight 4 is the application development platform for Windows Phone 7.1 (High performance
gaming is also supported through the XNA Framework.). Silverlight is an event driven
application and UI framework which has a lot of controls with awesome tool support for styling
them. 3D graphics are supported through perspective effects using PlaneProjection transform.
Use Silverlight for Windows Phone Development if:

    You want a XAML based, event driven application framework


www.windowsphonegeek.com
                                                                                                 14
Silverlight for Windows Phone Toolkit in Depth




    You want rapid creation of a Rich Internet Application-style user interface
    You want to use Windows Phone controls
    You want to embed video inside your application
    You want to use an HTML web browser control

Silverlight for Windows Phone supports core Silverlight capabilities in managed .NET code with
XAML including:

    High quality video and audio using a wide range of codecs, DRM and IIS Smooth Streaming
    Deep Zoom for enhanced reading and photo browsing experiences
    Vector and Bitmap Graphics and animation

Silverlight can access the unique capabilities of the phone including:

    Hardware acceleration for video and graphics
    Accelerometer for motion sensing
    Multi-touch
    Camera and microphone
    Location awareness
    Push notifications
    Native phone functionality

Silverlight can also utilize the XNA Framework for Audio capture and playback, Media Library
Access, and even accessing Xbox LIVE.

These capabilities are all exposed via managed code and can easily be targeted by adding
Windows Phone specific libraries to your existing Silverlight applications. You can then utilize
this functionality directly within your application, for example to data bind a map UI to the
current location or host an XNA Game Studio based game.

Developers build Silverlight applications and package them for submission to the Windows
Phone Marketplace where users can download them to run on the phone on a trial or purchase
basis. Silverlight for Windows Phone supports a built-in try/buy API to simplify the process of
converting a trial to full version for both developer and end consumer.

Developers can use the same tools they already use to develop for .NET, XAML and Silverlight
as development and design for the Silverlight applications on Windows Phone is supported
through Visual Studio 2010 and Expression Blend 4 for Windows Phone. In addition, existing



www.windowsphonegeek.com
                                                                                                   15
Silverlight for Windows Phone Toolkit in Depth




Silverlight and .NET code, libraries and mark-up can easily be re-used in Windows Phone
Silverlight applications. The Windows Phone Emulator is integrated with both Visual Studio and
Expression Blend 4 for Windows Phone and provides a means for deploying, debugging and
executing Silverlight applications without access to a physical device.

The first thing to consider when starting development of Windows Phone applications
is Installing Windows Phone Developer Tools. The package includes all necessary tools like:

    Visual Studio 2010 - Visual Studio is the IDE for building Windows Phone applications.
     Within it, developers can create Silverlight or XNA Framework programs that run on
     Windows Phone. For more information, see Visual Studio 2010 Express for Windows
     Phone.
    Expression Blend - In the same way that designers use Expression Blend to design Rich
     Internet Applications for the desktop browser, they can also design creative and unique
     Silverlight-based applications on a Windows Phone. Expression Blend for Windows Phone
     allows designers to create XAML-based interfaces for Windows Phone applications, whose
     behaviors can then be implemented by developers in Visual Studio. For more information,
     see Expression Blend.
    Windows Phone Emulator - A Windows Phone Emulator is integrated into Visual Studio
     and Expression Blend to make the testing and debugging of applications easier and more
     efficient. The emulator fully supports application deployment, debugging, and application
     execution. It includes support for GPU emulation and orientation change. For more
     information, see Windows Phone Emulator.

In addition to the built in controls you can also use some open source components/libraries.
Here is a list of some good ones provided by Microsoft:

    Silverlight for Windows Phone Toolkit - it includes some very helpful controls
     like AutoCompleteBox, ListPicker, LoopingSelector, LongListSelector, Page
     Transitions, GestureService/GestureListener, ContextMenu, DatePicker, TimePicker,
     ToggleSwitch, WrapPanel, PerformanceProgressBar, TiltEffect and more.
    Coding4Fun Toolkit - it includes About Prompt, Input Prompt, Progress Overlay (+
     ProgressBar), Round Button, Round Toggle Button, Memory Counter, TimeSpanPicker,
     ColorPicker and more. It also exposes some abstract classes, converters, binding helpers,
     data helpers etc.




www.windowsphonegeek.com
                                                                                                 16
Silverlight for Windows Phone Toolkit in Depth




Introduction to Silverlight for Windows
Phone Toolkit
Silverlight for Windows Phone Toolkit is a FREE Open Source Framework that offers developers
additional components for Windows Phone application development, designed to match the
rich user experience of the Windows Phone.

       NOTE: In Silverlight for Windows Phone 7.1 Toolkit all controls are distributed through
       Windows Phone class library projects built into assemblies which provide a reusable set of
       classes, components, controls, and user interface elements that can be incorporated into
Silverlight-based applications.



Components included in the Silverlight for
Windows Phone Toolkit
    AutoCompleteBox
    ContextMenu
    DatePicker
    DateTimeConverters
    ExpanderView
    Gestures
    HeaderedItemsControl
    HubTile
    ListPicker
    LocalizedResources
    LockablePivot
    LoopingSelector
    LongListSelector
    MultiselectList
    Page Transitions
    PerformanceProgressbar
    PhoneTextBox
    WrapPanel
    TiltEffect
    TimePicker
    ToggleSwitch




www.windowsphonegeek.com
                                                                                                    17
Silverlight for Windows Phone Toolkit in Depth




What's included in the source code?
The source package includes:

   Complete C# source code
   o Open Source Microsoft Public License
  Sample application
   o AutoCompleteBox
   o ContextMenu
   o DatePicker
   o DateTimeConverters
   o ExpanderView
   o Gestures
   o HeaderedItemsControl
   o HubTile
   o ListPicker
   o LocalizedResources
   o LockablePivot
   o LoopingSelector
   o LongListSelector
   o MultiselectList
   o Page Transitions
   o PerformanceProgressbar
   o PhoneTextBox
   o WrapPanel
   o TiltEffect
   o TimePicker
   o ToggleSwitch


Suggestions? Features? Questions?
    You can ask questions in the App Hub forums.
    You can add bugs or feature requests to the Issue Tracker:




www.windowsphonegeek.com
                                                                  18
Silverlight for Windows Phone Toolkit in Depth




Official Blogs & Tweets
Official: Windows Phone Developer Blog
Executives: Scott Guthrie, Joe Belfiore
Evangelists: Jaime Rodriguez, Pete Brown
Developers, Designers, Geeks: David Anson, Dave Relyea, Jeff Wilcox, Shawn Oster, Tim Heuer



What else will you need?
Before getting started using the Windows Phone Toolkit, you also need to install the following
tools:

    The Windows Phone Developer Tools
    Optional Visual Basic / VB tools download




www.windowsphonegeek.com
                                                                                                 19
Silverlight for Windows Phone Toolkit in Depth




Getting Started with the Silverlight for Windows
Phone Toolkit
In order to get started using Silverlight for Windows Phone Toolkit, just go to
http://silverlight.codeplex.com/releases/view/71550 (This is the currently official release of the
Silverlight for Windows Phone Toolkit - August 2011(7.1 SDK)). There you have several options:
     Installing the Silverlight for Windows Phone Toolkit - Aug 2011.msi
     Download the full Source Code .zip (Silverlight for Windows Phone Toolkit Source & Sample -
         Aug 2011.zip)
     Download only the XAP file (Silverlight for Windows Phone Toolkit Sample Application - Aug
         2011.xap)
     Install the Silverlight for Windows Phone Toolkit using NuGet




www.windowsphonegeek.com
                                                                                                     20
Silverlight for Windows Phone Toolkit in Depth




Option1: Install the Windows Phone Toolkit .msi
If you choose this option you will have to download the .msi file and install it:

Step1. Download Silverlight for Windows Phone Toolkit - Aug 2011.msi




Step2. Just run the installer as demonstrated below:




Step3. Check the “Accept” checkbox and press install:




www.windowsphonegeek.com
                                                                                    21
Silverlight for Windows Phone Toolkit in Depth




www.windowsphonegeek.com
                                                 22
Silverlight for Windows Phone Toolkit in Depth




Step4. After you have successfully installed the Windows Phone Toolkit you will find the
following folder on your hard drive: “Aug11” folder - Depending on the type of your OS in:




Here is what is in there:


      1.                                         - here you can find more information about the API




 2.                   – contains information related to the Microsoft Public License (Ms-PL)




www.windowsphonegeek.com
                                                                                                      23
Silverlight for Windows Phone Toolkit in Depth




 3.            - contains all necessary assemblies:




Option2: Download the “Silverlight for Windows
Phone Toolkit Source & Sample - Aug 2011.zip”
 Alternatively, if you do not want to install the .msi file you can download “Silverlight for
Windows Phone Toolkit Source & Sample - Aug 2011.zip” which contains a sample project as
well as all the necessary assemblies:




Step1. Download Silverlight for Windows Phone Toolkit Source & Sample - Aug 2011.zip




www.windowsphonegeek.com
                                                                                                24
Silverlight for Windows Phone Toolkit in Depth




Step2. Extract the zip file




Step3. You will find the full source code of Windows Phone Toolkit as well as a sample project:




Step4. Open the PhoneToolkit.sln file to run the whole solution with all projects inside.




After that you can rebuild “Microsoft.Phone.Controls.Toolkit” class library project and get the
generated assemblies from the “Bin” folder:




www.windowsphonegeek.com
                                                                                                  25
Silverlight for Windows Phone Toolkit in Depth




Option3: Download only the XAP file
One more option that you have is to download Silverlight for Windows Phone Toolkit Sample
Application - Aug 2011.xap file:




Option4: Install Windows Phone Toolkit using
NuGet
NuGet is a Visual Studio extension that makes it easy to install and manage libraries and tools in
Visual Studio projects. When you use NuGet to install a package, it copies the library files to
your solution and automatically updates your project (add references, change config files, etc).
If you remove a package, NuGet reverses whatever changes it made so that no clutter is left.
Windows Phone Toolkit Aug 2011 (SDK 7.1) is available on NuGet here:
http://nuget.org/List/Packages/SilverlightToolkitWP




www.windowsphonegeek.com
                                                                                                     26
Silverlight for Windows Phone Toolkit in Depth




How to use unofficial builds
As all open source projects published on CodePlex, the Silverlight for Windows Phone Toolkit is
updated regularly. Basically there are two types of change sets:

    Official: this is the officially published stable version which is usually reliable, carefully
     tested and recommended for application development.
    Unofficial: unofficial change sets usually contain small bug fixes or rarely - new features
     and breaking changes. It is not recommended to use unofficial change sets when
     developing your applications. Use them only if necessary and if there is no other solution
     of the problem.




www.windowsphonegeek.com
                                                                                                      27
Silverlight for Windows Phone Toolkit in Depth




Here is how you can use an unofficial change set:

Step1. Go to “Source Code” tab (http://silverlight.codeplex.com/SourceControl/list/changesets)
and select the desired change set you want to use as demonstrated below:




Step2. You can view all changes made since the last change set by pressing the “view diff” link
or you can directly press the “Download” link to start downloading the code:




Step3. Download the selected change set:




www.windowsphonegeek.com
                                                                                                  28
Silverlight for Windows Phone Toolkit in Depth




Step4. After extracting the zip you will find the full source code + sample project. In order to get
the updated assemblies just open the extracted “Aug 2011 Source and Samples” folder, open
the solution file and rebuild Microsoft.Phone.Controls.Toolkit project:




After rebuilding Microsoft.Phone.Controls.Toolkit a new Bin folder is generated in:
              C:\..\ Silverlight for Windows Phone Toolkit Source & Sample - Aug 2011




from where you can get the Microsoft.Phone.Controls.Toolkit.dll assembly.




www.windowsphonegeek.com
                                                                                                       29
Silverlight for Windows Phone Toolkit in Depth




How to use Windows Phone Toolkit in Visual Studio
The most common way to use the Silverlight for Windows Phone Toolkit controls and helper
classes is by adding a reference to “Microsoft.Phone.Controls.Toolkit.dll” in Visual Studio after
creating your Windows Phone application project. Here are the basic steps you need to follow:
Step1. Create a new Windows Phone 7.1 Application project in Visual Studio:




Step2. Go to “References” and select “Add Reference…”:




www.windowsphonegeek.com
                                                                                                    30
Silverlight for Windows Phone Toolkit in Depth




Step3. Select “Microsoft.Phone.Controls.Toolkit.dll”. You can find this assembly either in (If you
have installed the msi):




Or you can select it directly from the “...\Silverlight for Windows Phone Toolkit Source &
Sample - Aug 2011\WindowsPhone7\Bin\” if you have downloaded the “Silverlight for Windows
Phone Toolkit Source & Sample - Aug 2011.zip” instead.




www.windowsphonegeek.com
                                                                                                     31
Silverlight for Windows Phone Toolkit in Depth




Step4. Go to the XAML part of your page and include the “toolkit” namespace. After that you
can add the desired controls like for example:




www.windowsphonegeek.com
                                                                                              32
Silverlight for Windows Phone Toolkit in Depth




How to add Windows Phone Toolkit Controls to the
Visual Studio Toolbox
Visual Studio Toolbox support is important when you want to "drag" and "drop" controls into
the visual designer instead of writing any XAML code by hand. Adding a control from the
toolbox also automatically includes the necessary namespaces (xmlns) to your page. So as a
result you can write a simple Windows Phone application just with a few mouse clicks and “no
code”. However Windows Phone Toolkit controls are not automatically added to the Visual
Studio Toolbox when you add a reference to Microsoft.Phone.Controls.Toolkit.dll assembly so
you will need to add them on your own.
 In short, instead of adding the “toolkit” namespace and the desired control on your own (as
described in the previous section) you could add all controls to the Visual Studio Toolbox and
use them via “Drag&Drop”.
In order to add the Windows Phone Toolkit Controls to the toolbox just follow the steps:

Step1. Create a new Windows Phone application project

Step2. Open the “Toolbox” tool window, right click and select “Add Tab”




www.windowsphonegeek.com
                                                                                                 33
Silverlight for Windows Phone Toolkit in Depth




Step3. Give a name to the newly created Tab like for example “WPToolkit”:




Step4. Again press the mouse right button but this time select the “Choose Items…” option
from the context menu:




Step5. A new window will appear from where you can select all the controls that you want to
be visible in the Visual Studio Toolbox (Note that you can select all controls or only a part of
them):




www.windowsphonegeek.com
                                                                                                   34
Silverlight for Windows Phone Toolkit in Depth




Step6. Press OK and go back to the “Toolbox” section. Now you should see all Windows Phone
Toolkit controls there:




www.windowsphonegeek.com
                                                                                             35
Silverlight for Windows Phone Toolkit in Depth




Step7. After that you can simply drag and drop the desired control onto the design surface:




Example:
Let`s say that we have dragged/dropped a DatePicker control. If you take a look at the
generated XAML code you will notice the following namespace:

xmlns:toolkit="clrnamespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.To
olkit"


This means that Visual Studio has automatically included the necessary namespace as well as an
instance of the DatePicker control (all the necessary XAML code has been automatically
generated):




www.windowsphonegeek.com
                                                                                                 36
Silverlight for Windows Phone Toolkit in Depth




You can now customize the DatePicker control either by changing its properties directly in code
(XAML or C#/VB) or by using the Visual Studio Properties tool window. If “Properties Window”
is not visible by default you can open it either by pressing “Ctrl+W,P” or through the View tab
by selecting “View->Properties Window”:




www.windowsphonegeek.com
                                                                                                  37
Silverlight for Windows Phone Toolkit in Depth




How to use Windows Phone Toolkit in Expression
Blend
Expression Blend 4 for Windows Phone is automatically installed when installing the Windows
Phone Developer Tools. Basically Microsoft Expression Blend is a user interface design tool with
lots of capabilities. Key components of Expression Blend, including Behaviors, Visual State
Manager, transition effects, and SketchFlow (Expression Blend 4 includes SketchFlow in the
Expression Studio 4 Ultimate product only), coupled with the speed and flexibility of this
modern workflow, challenge you to push boundaries and work beyond the limits of what you
thought possible.(for more information visit the official web page:
http://www.microsoft.com/expression/products )




www.windowsphonegeek.com
                                                                                                   38
Silverlight for Windows Phone Toolkit in Depth




           In order to get started using the Windows Phone Toolkit Controls in Expression Blend
just follow the steps below:

Step1: Open Expression Blend 4 and go to “New Project”. Here you can choose between several
Windows Phone application types:

    Windows Phone Application
    Windows Phone Database Application
    Windows Phone Panorama Application
    Windows Phone Pivot Application
    Windows Phone Control Library




Step2. Create a new Windows Phone application project and go to the “References” section,
right click and select “Add Reference…” to select “Microsoft.Phone.Controls.Toolkit.dll” as
demonstrated below:




www.windowsphonegeek.com
                                                                                                  39
Silverlight for Windows Phone Toolkit in Depth




Step3. After you have added the reference to “Microsoft.Phone.Controls.Toolkit.dll”, just go to
the “Assets” tab then “Controls” and you will see all controls there:




Step4. In order to use the Toolkit`s controls just “Drag and Drop” the desired control onto the
design surface:




www.windowsphonegeek.com
                                                                                                  40
Silverlight for Windows Phone Toolkit in Depth




Step5. If you switch to XAML view you will notice that Expression Blend has automatically
included the
 xmlns:toolkit="clrnamespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"
namespace on top of the page:




Step6. You can set different values to the target control properties through the visual designer
using the Properties tab:




www.windowsphonegeek.com
                                                                                                   41
Silverlight for Windows Phone Toolkit in Depth




AutoCompleteBox
Overview
Basically, AutoCompleteBox is a control which shows suggestions in a drop-down, when the
user types text into it. It is composed of a text box for text entry and a drop down. There is a
rich set of properties for customization and item display, data binding support, and all the
necessary logic to provide suggestions and completion.




Getting Started
To begin using AutoCompleteBox first add a reference to the
Microsoft.Phone.Controls.Toolkit.dll assembly in your Windows Phone application project.

       NOTE: Microsoft.Phone.Controls.Toolkit.dll assembly is installed with the toolkit and you
       can find it in:
       For 32-bit systems:
       C:\Program Files\Microsoft SDKs\Windows
       Phone\v7.1\Toolkit\Aug11\Bin\Microsoft.Phone.Controls.Toolkit.dll
       For 64-bit systems:
       C:\Program Files (x86)\Microsoft SDKs\Windows
       Phone\v7.1\Toolkit\Aug11\Bin\Microsoft.Phone.Controls.Toolkit.dll

       Alternatively you can select it directly from the “...\Silverlight for Windows Phone Toolkit
       Source & Sample - Aug 2011\Bin\” if you have downloaded the “Silverlight for Windows
       Phone Toolkit Source & Sample - Aug 2011.zip” instead.




www.windowsphonegeek.com
                                                                                                      42
Silverlight for Windows Phone Toolkit in Depth




You can create an instance of the AutoCompleteBox control either in XAML or with C#/VB.

         Define AutoCompleteBox in XAML: you will have to add the following namespace
          declaration (for example):

xmlns:toolkit="clr-
namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"

XAML
<toolkit:AutoCompleteBox x:Name="acBox" Height="80"/>




         NOTE: Make sure that your page declaration includes the "toolkit" namespace! You can
         do this by using the Visual Studio Toolbox, Expression Blend Designer or just include it on
         your own.

         Create an instance of AutoCompleteBox in C#: you will have add the following using
          directive:

using Microsoft.Phone.Controls;

C#
AutoCompleteBox acBox = new AutoCompleteBox();



Next assign the following collection of strings to the ItemsSource property in order to populate
the AutoCompleteBox with sample data:

C#

List<string> cities = new List<string>();
cities.Add("Barcelona");
cities.Add("Bogota");
cities.Add("Berlin");
cities.Add("London");
cities.Add("Las Vegas");
cities.Add("New York");
cities.Add("New Castle");
cities.Add("Sofia");
cities.Add("Paris");
cities.Add("Prague");
cities.Add("Madrid");
cities.Add("Milan");
this.acBox.ItemsSource = cities;




www.windowsphonegeek.com
                                                                                                       43
Silverlight for Windows Phone Toolkit in Depth




Key Properties
FilterMode
FilterMode is a dependency property of type AutoCompleteFilterMode which is used to filter
items specified by the ItemsSource for display in the drop-down. Its default value is
AutoCompleteFilterMode.StartsWith.

      NOTE: Use the FilterMode property to specify how possible matches are filtered. For
      example, possible matches can be filtered in a predefined or custom way. The search
      mode is automatically set to Custom if you set the ItemFilter property.

Example:
Let’s say that we want to implement a case-sensitive search, and then all we need to do is set
the FilterMode property as demonstrated in the example below:

C#
this.acBox.FilterMode = AutoCompleteFilterMode.StartsWithCaseSensitive;




www.windowsphonegeek.com
                                                                                                 44
Silverlight for Windows Phone Toolkit in Depth




 As you can see in the first example we just type a lower case letter and nothing appears in the
popup. In the second example we type an upper case letter and the suggested names appear
immediately.

ItemFilter
ItemFilter is a dependency property of type AutoCompleteFilterPredicate<object>. Its value is a
custom method that uses the user-entered text to filter the items. The default is null.

      NOTE: The filter mode is automatically set to Custom if you set the ItemFilter property.
      Use ItemFilter to provide custom object filtering for items displayed in the drop-down.
      Alternatively, you should use the TextFilter property to provide custom text filtering.

    public delegate bool AutoCompleteFilterPredicate<T>(string search, T item);

Represents the filter used by the AutoCompleteBox control to determine whether an item is a
possible match for the specified text. Returns true to indicate that the item is a match for the
search, otherwise false.
  search - the string used as the basis for filtering
  item - the item that is compared with the “search" parameter.
  T - the type used for filtering the AutoCompleteBox. This type can be either a string or an
object.

Example:
Let’s say we want to implement a custom search that is based on the last letters. Then all we
need to do is just to add the following code:

C#

this.acBox.ItemFilter = SearchCountry;
       //...
bool SearchCountry(string search, object value)
{
       if (value != null)
       {
              // Look for a match in the last letter.
              if (value.ToString().ToLower().EndsWith(search))
                     return true;
       }
       // If no match, return false.
       return false;
}




www.windowsphonegeek.com
                                                                                                   45
Silverlight for Windows Phone Toolkit in Depth




When we type the letter "s" the suggested names that end with "s" appear immediately (the
search looks for a match in the last letters). In a similar way you can add your own custom
search filtering that fits in your scenario.

TextFilter
TextFilter is a dependency property of type AutoCompleteFilterPredicate<string>. Its value is a
custom method that uses the user-entered text to filter items for display in the drop-down.
(Take a look at the previous point for AutoCompleteFilterPredicate).

      NOTE: The search mode is automatically set to Custom if you set the TextFilter. Use
      TextFilter to provide custom string filtering for items displayed in the drop-down.
      Alternatively, you should use the ItemFilter property to provide custom object filtering


Example:
Let’s say we want to filter the names by their length. So we will need some kind of custom filter
like the following:




www.windowsphonegeek.com
                                                                                                    46
Silverlight for Windows Phone Toolkit in Depth




C#

this.acBox.TextFilter += CustomFilter;
                     //...
bool CustomFilter(string search, string value)
{
       return (value.Length > 6);
}




As you can see when you type some letter only the names with length greater that 6 appear as
suggested results.

MinimumPopulateDelay
MinimumPopulateDelay is a dependency property of type int. The default is 0. It gets or sets
the minimum delay, in milliseconds after text is typed in the text box, before the
AutoCompleteBox control populates the list of possible matches in the drop-down.

MinimumPrefixLength
MinimumPrefixLength is a dependency property of type int. The default is 1. It gets or sets the
minimum number of characters required to be entered in the text box before the
AutoCompleteBox displays possible matches.



www.windowsphonegeek.com
                                                                                                  47
Silverlight for Windows Phone Toolkit in Depth




        NOTE: If you set MinimumPrefixLength to -1, the AutoCompleteBox will not provide
        possible matches. There is no maximum value, but setting MinimumPrefixLength to value
        that is too large will prevent the AutoCompleteBox from providing possible matches as
well.

Example:
Let`s say that we want to view the suggestions after the user enter at least 2 letters. The code
for accomplishing this is as follows:

C#
this.acBox.MinimumPrefixLength = 2;




In the first case when you enter a single letter nothing happens. In the second case the
suggested results appear in the popup after entering at least 2 letters.

SearchText
SearchText is a dependency property that gets the text that is used to filter items in the
ItemsSource item collection.




www.windowsphonegeek.com
                                                                                                   48
Silverlight for Windows Phone Toolkit in Depth




       NOTE: The SearchText value is typically the same as the Text property, but is set after the
       TextChanged event occurs and before the Populating event.

TextBoxStyle
TextBoxStyle is a dependency property that gets or sets the Style applied to the text box portion of the
AutoCompleteBox control. The default is null.


Text
Text is a dependency property of type string that represents the text in the text box portion of
the AutoCompleteBox control.

IsDropDownOpen
IsDropDownOpen is a dependency property of type bool that gets or sets a value indicating
whether the drop-down portion of the control is open.

IsTextCompletionEnabled
IsTextCompletionEnabled is a dependency property of type bool that gets or sets a value
indicating whether the first possible match found during the filtering process will be displayed
automatically in the textbox. The default is false.

InputScope
InputScope is a dependency property of type InputScope. It determines the InputScope of the
Text template part of the AutoCompleteBox. I.e. Number, Password, Text, etc.


      NOTE: Although AutoCompleteBox is not an ItemsControl (it derives from Control instead)
     it expose some of the typical ItemsControl properties like: ItemContainerStyle,
ItemTemplate and ItemsSource!

ItemContainerStyle
ItemContainerStyle is a dependency property of type Style. It determines the Style that is
applied to the selection adapter contained in the drop-down portion of the AutoCompleteBox
control.

ItemTemplate
You use the ItemTemplate property to specify the visualization of the data objects in the drop-
down portion of the AutoCompleteBox control. If your AutoCompleteBox is bound to a




www.windowsphonegeek.com
                                                                                                           49
Silverlight for Windows Phone Toolkit in Depth




collection and you do not provide specific display instructions by using a DataTemplate, the
resulting UI of each item is a string representation of each object in the underlying collection.


ItemsSource
Gets or sets a collection that is used to generate the items for the drop-down portion of the
AutoCompleteBox control.

SelectedItem
Gets or sets the selected item in the drop-down.

      NOTE: Regarding data binding AutoCompleteBox exposes ValueMemberBinding and
      ValueMemberPath properties as well.



Key Events
Populated
Occurs when the AutoCompleteBox has populated the drop-down with possible matches based
on the Text property.
Example:
C#

this.acBox.Populated += new PopulatedEventHandler(acBox_Populated);
void acBox_Populated(object sender, PopulatedEventArgs e)
{
       // …
}




Populating
Occurs when the AutoCompleteBox is populating the drop-down with possible matches based
on the Text property.
Example:
C#

this.acBox.Populating += new PopulatingEventHandler(acBox_Populating);
void acBox_Populating(object sender, PopulatingEventArgs e)
{
       // …
}




www.windowsphonegeek.com
                                                                                                    50
Silverlight for Windows Phone Toolkit in Depth




      NOTE: If the event is canceled, by setting the PopulatingEventArgs. Cancel property to true, the
      AutoCompleteBox will not automatically populate the drop-down. In this case, if you want possible
      matches to appear, you must provide the logic for populating the drop-down.



TextChanged
Occurs when the text in the text box portion of the AutoCompleteBox changes.
Example:
C#

this.acBox.TextChanged += new RoutedEventHandler(acBox_TextChanged);
void acBox_TextChanged(object sender, RoutedEventArgs e)
{
       //…
}



DropDownOpening
Occurs when the IsDropDownOpen is changed to true but the AutoCompleteBox is still not
opened.
Example:
C#
this.acBox.DropDownOpening += new
RoutedPropertyChangingEventHandler<bool>(box_DropDownOpening);
void acBox_DropDownOpening(object sender,
RoutedPropertyChangingEventArgs<bool> e)
{
       //...
}



DropDownOpened
Occurs when the AutoCompleteBox is opened and the IsDropDownOpen is changed to true.
Example:
C#
this.acBox.DropDownOpened += new
System.Windows.RoutedPropertyChangedEventHandler<bool>(acBox_DropDownOpened);
void acBox_DropDownOpened(object sender,
System.Windows.RoutedPropertyChangedEventArgs<bool> e)
{
       //...
}




www.windowsphonegeek.com
                                                                                                          51
Silverlight for Windows Phone Toolkit in Depth




DropDownClosing
Occurs when the IsDropDownOpen is changed to false but the AutoCompleteBox is still opened.
Example:
C#
this.acBox.DropDownClosing += new
RoutedPropertyChangingEventHandler<bool>(acBox_DropDownClosing);
void acBox_DropDownClosing(object sender,
RoutedPropertyChangingEventArgs<bool> e)
{
       //...
}



DropDownClosed
Occurs when the AutoCompleteBox is closed and the IsDropDownOpen is changed to false.
Example:
C#
this.acBox.DropDownClosed += new
System.Windows.RoutedPropertyChangedEventHandler<bool>(acBox_DropDownClosed);
void acBox_DropDownClosed(object sender,
System.Windows.RoutedPropertyChangedEventArgs<bool> e)
{
       //...
}



SelectionChanged
Occurs when the Selected item in the text box portion of the AutoCompleteBox has changed.
Example:
C#
this.acBox.SelectionChanged += new
System.Windows.Controls.SelectionChangedEventHandler(acBox_SelectionChanged);
void acBox_SelectionChanged(object sender,
System.Windows.Controls.SelectionChangedEventArgs e)
{
       //...
}




Key Methods
PopulateComplete()
Notifies the AutoCompleteBox that its ItemsSource property has been set and the data can be
filtered to provide possible matches in the drop-down.


www.windowsphonegeek.com
                                                                                              52
Silverlight for Windows Phone Toolkit in Depth




      NOTE: Call this method when you are providing custom population of the drop-down
      portion of the AutoCompleteBox, to signal the control that you are done with
      the population process. Typically, you use PopulateComplete() when the population
process is a long-running process and you want to cancel built-in filtering of the ItemsSource
items. In this case, you can handle the Populated event and set PopulatingEventArgs.Cancel to
true. When the long-running process has completed you call PopulateComplete() to indicate
that the drop-down is populated.



Data Binding AutoCompleteBox
This example demonstrates how to populate the AutoCompleteBox control with data using
data binding. We will implement a sample that shows suggestions for different mobile phones
including images and text descriptions.

      Defining the Data Source
Here are the steps we will follow in order to create a data source:

Step1. Define the business/data class:

The first step is to define the data class. Let’s create a sample”WP7Phone" class which exposes
the following properties:

C#
public class WP7Phone
{

       public string Image
       {
              get;
              set;
       }

       public string Name
       {
              get;
              set;
       }

       public override string ToString()
       {
              return "Selected Phone: " +Name;
       }
}




www.windowsphonegeek.com
                                                                                                  53
Silverlight for Windows Phone Toolkit in Depth




      NOTE: It is important to override ToString() method because we will have to implement a
      custom text filter method that evaluates the string returned from the ToString method of
      the WP7Phone object. The custom filter returns matches from WP7Phone`s Name. I.e.
the displayed value in the Textbox area will be the returned string!

Step2. Create a new Images folder and add some images in it (with a build action set to
Content) which will be shown in the AutoCompleteBox dropdown:




Step3. Create a sample collection with items of type WP7Phone:

C#
public MainPage()
{
       InitializeComponent();

         List<WP7Phone> dataSource = new List<WP7Phone>()
         {
         new WP7Phone(){Image="/Images/DellVenue.jpg", Name = "Dell Venue"},
         new WP7Phone(){Image="/Images/HTChd7.jpg", Name = "HTC HD 7"},
         new WP7Phone(){Image="/Images/HTCMozart.jpg", Name = "HTC Mozart"},
         new WP7Phone(){Image="/Images/LGOptimus.jpg", Name = "LG Optimus"},
         new WP7Phone(){Image="/Images/LGQuantumC900.jpg", Name = "LG Quantum C
900"},
         };
               //...
}




        Data binding AutoCompleteBox

Step1. Define AutoCompleteBox in XAML

We will define an AutoCompleteBox with FilterMode set to “Custom” because we want to show
a custom data of type “WP7Phone”. Next we will define a custom ItemTemplate with an Image
data bound to the Image property of our “WP7Phone” class and a TextBlock data bound to the
Name property of the same class. Here is how the code should look like:




www.windowsphonegeek.com
                                                                                                 54
Silverlight for Windows Phone Toolkit in Depth




XAML
<toolkit:AutoCompleteBox x:Name="acBox" FilterMode="Custom">.
       <toolkit:AutoCompleteBox.ItemTemplate>
              <DataTemplate>
                     <StackPanel Orientation="Horizontal">
                            <Image Source="{Binding Image}" Stretch="None"
Margin="0,0,5,5"/>
                            <TextBlock Text="{Binding Name}"/>
                     </StackPanel>
              </DataTemplate>
       </toolkit:AutoCompleteBox.ItemTemplate>
</toolkit:AutoCompleteBox>



Step2. Populate the AutoCompleteBox with data through its ItemsSource property:

C#
public MainPage()
{
       InitializeComponent();
       //...

       this.acBox.ItemsSource = dataSource;
}




Step3. Add a custom ItemFilter to the AutoCompleteBox.

We will add a custom delegate named SearchPhones in which we will search for a possible
match depending on the entered letter. (i.e. if the string starts with the entered letter).

C#
public MainPage()
{
       InitializeComponent();
       //...

       this.acBox.ItemFilter = SearchPhones;
}

bool SearchPhones(string search, object value)
{
       if (value != null)
       {
              WP7Phone datasourceValue = value as WP7Phone;
              string name = datasourceValue.Name;
              if (name.ToLower().StartsWith(search.ToLower()))
                     return true;
       }
       //... If no match, return false.
       return false;
}


www.windowsphonegeek.com
                                                                                              55
Silverlight for Windows Phone Toolkit in Depth




Step4. Build and run the project. Here is how the final result should look like:

Let’s say we type “htc” in the TextBox area of the AutoCompleteBox. As you can see on the screen shots
below two suggestions are offered in the dropdown area. If we select “HTC Mozart” the following text
will appear in the TextBox area: “Selected Phone: HTC Mozart”. (Note that this string is returned by the
overridden ToString() method in the WP7Phone class).




www.windowsphonegeek.com
                                                                                                           56
Silverlight for Windows Phone Toolkit in Depth




Data Binding AutoCompleteBox via ValueMemberBinding
Alternatively if you do not want to use a Custom filter then there is no need to override
ToString() method in you data class because you can use ValueMemberBinding instead. This
example uses the same data as the previous one the only difference here is that we do not use
any custom filter.

      Data Source

Here is how the data source should look like:

C#
public MainPage()
{
       InitializeComponent();

       List<WP7Phone> dataSource = new List<WP7Phone>()
       {
       new WP7Phone(){Image="/Images/DellVenue.jpg", Name = "Dell Venue"},
       new WP7Phone(){Image="/Images/HTChd7.jpg", Name = "HTC HD 7"},
       new WP7Phone(){Image="/Images/HTCMozart.jpg", Name = "HTC Mozart"},
       new WP7Phone(){Image="/Images/LGOptimus.jpg", Name = "LG Optimus"},
       new WP7Phone(){Image="/Images/LGQuantumC900.jpg", Name = "LG Quantum C 900"},
       };

       this.acBox.ItemsSource = dataSource;
}

public class WP7Phone
{

       public string Image
       {
              get;
              set;
       }

       public string Name
       {
              get;
              set;
       }
}



      Data Binding

Here is how the data bound AutoCompleteBox should look like:



www.windowsphonegeek.com
                                                                                                57
Silverlight for Windows Phone Toolkit in Depth




XAML
<toolkit:AutoCompleteBox x:Name="acBox" FilterMode="StartsWith"
ValueMemberBinding="{Binding Name}">
       <toolkit:AutoCompleteBox.ItemTemplate>
              <DataTemplate>
                     <StackPanel Orientation="Horizontal">
                            <Image Source="{Binding Image}" Stretch="None"
Margin="0,0,5,5"/>
                            <TextBlock Text="{Binding Name}"/>
                     </StackPanel>
              </DataTemplate>
       </toolkit:AutoCompleteBox.ItemTemplate>
</toolkit:AutoCompleteBox>




    Result
   Here is how the final result should look like:




www.windowsphonegeek.com
                                                                             58
Silverlight for Windows Phone Toolkit in Depth




ContextMenu
Overview
Basically, ContextMenu is a dynamic control that appears whenever a user taps and holds on
any item. It is used in areas like for example the application list, where if you tap and hold an
application you get the option to pin it to the start menu, uninstall, etc.




Getting Started
To begin using ContextMenu first add a reference to the Microsoft.Phone.Controls.Toolkit.dll
assembly in your Windows Phone application project.

       NOTE: Microsoft.Phone.Controls.Toolkit.dll assembly is installed with the toolkit and you
       can find it in:
       For 32-bit systems:
       C:\Program Files\Microsoft SDKs\Windows
       Phone\v7.1\Toolkit\Aug11\Bin\Microsoft.Phone.Controls.Toolkit.dll
       For 64-bit systems:
       C:\Program Files (x86)\Microsoft SDKs\Windows
       Phone\v7.1\Toolkit\Aug11\Bin\Microsoft.Phone.Controls.Toolkit.dll

       Alternatively you can select it directly from the “...\Silverlight for Windows Phone Toolkit
       Source & Sample - Aug 2011\Bin\” if you have downloaded the “Silverlight for Windows
       Phone Toolkit Source & Sample - Aug 2011.zip” instead.




www.windowsphonegeek.com
                                                                                                      59
Silverlight for Windows Phone Toolkit in Depth



You can create an instance of the ContextMenu either in XAML or with C#/VB.

         Define a ContextMenu in XAML: you have to add the following namespace declaration
          (for example):

xmlns:toolkit="clr-
namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"

XAML

<toolkit:ContextMenuService.ContextMenu>
       <toolkit:ContextMenu>
              <toolkit:MenuItem Header="Item1"/>
              <toolkit:MenuItem Header="Item2"/>
              <toolkit:MenuItem Header="Item3"/>
       </toolkit:ContextMenu>
</toolkit:ContextMenuService.ContextMenu>




         NOTE: Make sure that your page declaration includes the "toolkit" namespace! You can
         do this by using Visual Studio Toolbox, Expression Blend Designer or just include it on your
         own.


         Create an instance of the ContextMenu control in C#/VB: just add the following using
          directive:

using Microsoft.Phone.Controls;

C#

ContextMenu contextMenu = new ContextMenu();
MenuItem menuItem1 = new MenuItem() { Header = "Item1};
MenuItem menuItem2 = new MenuItem() { Header = "Item2”};
MenuItem menuItem3 = new MenuItem() { Header = "Item3};
contextMenu.Items.Add(menuItem1);
contextMenu.Items.Add(menuItem2);
contextMenu.Items.Add(menuItem3);
ContextMenuService.SetContextMenu(this.ContentPanel,contextMenu);




Key Properties
IsOpen
IsOpen is a dependency property of type bool. It gets or sets a value indicating whether the
ContextMenu is visible.


www.windowsphonegeek.com
                                                                                                        60
Silverlight for Windows Phone Toolkit in Depth




IsZoomEnabled
IsZoomEnabled is a dependency property of type bool. It gets or sets a value indicating
whether the background will zoom out when the ContextMenu is open.
Example:
XAML

<toolkit:ContextMenu VerticalOffset="100.0" IsZoomEnabled="True" x:Name="menu"/>




IsFadeEnabled
IsFadeEnabled is a dependency property of type bool. It gets or sets whether the background
will fade when the ContextMenu is open.
Example:
XAML

<toolkit:ContextMenu VerticalOffset="100.0" IsFadeEnabled="True" x:Name="menu"/>




ItemContainerStyle
ItemContainerStyle is a dependency property of type Style. It gets or sets the style that is
applied to the container element generated for each item.
Example:
XAML

<toolkit:ContextMenu x:Name="databoundMenu">
       <toolkit:ContextMenu.ItemContainerStyle>
              <Style TargetType="toolkit:MenuItem">
                     <Setter Property="Background" Value="YellowGreen" />
                     <Setter Property="Margin" Value="5" />
              </Style>
       </toolkit:ContextMenu.ItemContainerStyle>
</toolkit:ContextMenu>




VerticalOffset
VerticalOffset is a dependency property of type double. It gets or sets the vertical distance
between the target origin and the popup alignment point.




www.windowsphonegeek.com
                                                                                                61
Silverlight for Windows Phone Toolkit in Depth




Example:
C#

<toolkit:ContextMenu VerticalOffset="100.0" IsZoomEnabled="True" x:Name="menu"/>




RegionOfInterest
RegionOfInterest is a dependency property of type “Rect?”. It gets or sets the region of interest
expressed in the coordinate system of the root visual. A context menu will try to position itself
outside the region of interest. If null, the owner's bounding box is considered the region of
interest.


Key Events
Closed
The Closed event occurs when a particular instance of a ContextMenu closes.
Example:
C#

this.menu.Closed += new RoutedEventHandler(menu_Closed);
void menu_Closed(object sender, RoutedEventArgs e)
{
       //add some code here
}



Opened
The Opened event occurs when a particular instance of a ContextMenu opens.
Example:
C#

this.menu.Opened += new RoutedEventHandler(menu_Opened);
void menu_Opened(object sender, RoutedEventArgs e)
{
       //add some code here
}




www.windowsphonegeek.com
                                                                                                    62
Silverlight for Windows Phone Toolkit in Depth




MenuItem
MenuItem represents a selectable item inside a ContextMenu.

       NOTE: A ContextMenu contains a collection of MenuItem objects. To select a MenuItem in
       a ContextMenu, set the IsSelected property to true. Bind a MenuItem to data by binding
       the ItemsSource property of a ContextMenu to a data source.


MenuItem Key Properties
Command
Command is a dependency property of type ICommand. It gets or sets the command associated
with the menu item.


CommandParameter
CommandParameter is a dependency property of type object. It gets or sets the parameter to
pass to the Command property of a MenuItem.


Header
Header is a dependency property of type object. It gets or sets the item that labels the control.
The default value is null. Note that this property is used when you populate the ContextMenu
with MenuItems rather than when using binding.
Example:
XAML

<toolkit:ContextMenuService.ContextMenu>
       <toolkit:ContextMenu>
              <toolkit:MenuItem Header="AddItem"/>
              <toolkit:MenuItem>
                     <toolkit:MenuItem.Header>
                            <StackPanel Orientation="Horizontal">
                                   <TextBlock Text="Delete Item"/>
                                   <Image
Source="Images/appbar.delete.rest.png"/>
                            </StackPanel>
                     </toolkit:MenuItem.Header>
              </toolkit:MenuItem>
       </toolkit:ContextMenu>
</toolkit:ContextMenuService.ContextMenu>




www.windowsphonegeek.com
                                                                                                    63
Silverlight for Windows Phone Toolkit in Depth




HeaderTemplate
HeaderTemplate is a dependency property of type DataTemplate. It gets or sets a data
template that is used to display the contents of the control's header.


ItemContainerStyle
ItemContainerStyle is a dependency property of type Style. It gets or sets the style that is
applied to the container element generated for each item.



MenuItem Key Events
Click
The Click event occurs when a MenuItem is clicked.
Example:
XAML
<toolkit:MenuItem Header="Add"      Click="MenuItem_Click"/>




C#

private void MenuItem_Click(object sender, RoutedEventArgs e)
{
       //add some code here
}




Populating ContextMenu with MenuItems
This example demonstrates how to populate a ContextMenu with data in the easiest way using
MenuItems:

XAML

<Button Content="OpenContextMenu" Height="100" Width="270">
       <toolkit:ContextMenuService.ContextMenu>
              <toolkit:ContextMenu>
                     <toolkit:MenuItem Header="Add" Click="MenuItem_Click"/>
                     <toolkit:MenuItem Header="Update"
Click="MenuItem_Click"/>
                     <toolkit:MenuItem Header="Delete"



www.windowsphonegeek.com
                                                                                               64
Silverlight for Windows Phone Toolkit in Depth



Click="MenuItem_Click"/>
              </toolkit:ContextMenu>
       </toolkit:ContextMenuService.ContextMenu>
</Button>




C#

private void MenuItem_Click(object sender, RoutedEventArgs e)
{
       MenuItem menuItem = (MenuItem)sender;
       MessageBox.Show("You chose to " + menuItem.Header.ToString(),
"Result",MessageBoxButton.OK);
}



When the user taps and holds the "OpenContextMenu" button, as a result a context menu
appears from where you can select from three options. After you choose an item a MessageBox
appears with information about the selected operation.

The result can be seen on the following screen shots:




www.windowsphonegeek.com
                                                                                              65
Silverlight for Windows Phone Toolkit in Depth




Data Binding ContextMenu
This example demonstrates how to populate ContextMenu with data via data binding. We will
also add an ItemContainerStyle in order to change the background color of menu items.

        Defining the Data Source

We will create a simple collection with items of type “string”:
C#

List<string> menuItems = new List<string>() { "Copy", "Paste", "Cut" };



        Databinding ContextMenu

We will add a data bound ContextMenu inside a Button control.
Step1. Define a ContextMenu instance inside a Button control. Next add the following
ItemContainerStyle :
XAML

<Button Content="DataBinding" Height="100" Width="270">
    <toolkit:ContextMenuService.ContextMenu>
        <toolkit:ContextMenu x:Name="databoundMenu">
              <toolkit:ContextMenu.ItemContainerStyle>
                     <Style TargetType="toolkit:MenuItem">
                         <Setter Property="Background" Value="YellowGreen" />
                         <Setter Property="Margin" Value="5" />
                     </Style>
              </toolkit:ContextMenu.ItemContainerStyle>
         </toolkit:ContextMenu>
    </toolkit:ContextMenuService.ContextMenu>
</Button>


Step2. Populate the ContextMenu with data through its ItemsSource property:
C#

this.databoundMenu.ItemsSource = menuItems;



The result can be seen on the following screen shots:




www.windowsphonegeek.com
                                                                                            66
Silverlight for Windows Phone Toolkit in Depth




Using ContextMenu inside ListBox ItemTemplate
(DataTemplate)
This example demonstrates how you can add ContextMenu inside ListBox ItemTemplate when
having a data bound ListBox.

        Defining the Data Source

Here are the steps we will follow in order to create a data source:

Step1. Define the business/data class:

The first step is to define the data class. Let’s create a sample ”SampleData" class which
exposes the following properties:

C#

public class SampleData
{
       public string Text
       {
              get;
              set;
       }

         public string ImageUri
         {
                get;
                set;
         }
}




www.windowsphonegeek.com
                                                                                             67
Silverlight for Windows Phone Toolkit in Depth




Step2. Create a new Images folder and add some images in it (with build action set to Content)
which will be used later:




Step3. Create a sample collection with items of type “SampleData”:

C#

public MainPage()
{
       InitializeComponent();

       ObservableCollection<SampleData> dataSource = new
ObservableCollection<SampleData>();

       dataSource.Add(new SampleData() { ImageUri =
"/Images/appbar.back.rest.png", Text = "Item1" });
       dataSource.Add(new SampleData() { ImageUri =
"/Images/appbar.delete.rest.png", Text = "Item2" });
       dataSource.Add(new SampleData() { ImageUri =
"/Images/appbar.download.rest.png", Text = "Item3" });

         //...
}



        Data binding the ListBox control

Step1. Define a ListBox control with a ContextMenu placed inside its ItemTemplate. The
ContextMenu will consist of two MenuItems each one with “Click” handler set to
“MenuItem_Click”:


XAML

<ListBox x:Name="listBox">
 <ListBox.ItemTemplate>
   <DataTemplate>
     <StackPanel x:Name="sp">
       <toolkit:ContextMenuService.ContextMenu>
         <toolkit:ContextMenu>
           <toolkit:MenuItem Header="Add Color" Click="MenuItem_Click"/>
           <toolkit:MenuItem Header="Remove Color" Click="MenuItem_Click"/>
         </toolkit:ContextMenu
       </toolkit:ContextMenuService.ContextMenu>



www.windowsphonegeek.com
                                                                                                 68
Silverlight for Windows Phone Toolkit in Depth



       <Image Source="{Binding ImageUri}" Stretch="None" />
       <TextBlock Text="{Binding Text}" />
    </StackPanel>
  </DataTemplate>
 </ListBox.ItemTemplate>
</ListBox>



Step2. Populate the ListBox with data through its ItemsSource property:

C#

public MainPage()
{
       InitializeComponent();
       //...
       this.listBox.ItemsSource = dataSource;
}



Step3. Add the following code inside “MenuItem_Click” handler:

You can highlight the ListBox SelectedItem and also get a reference to the ListBox tapped item
from the ContextMenu Click handler in this way:

C#

private void MenuItem_Click(object sender, RoutedEventArgs e)
{
       string header = (sender as MenuItem).Header.ToString();

       ListBoxItem selectedListBoxItem =
this.listBox.ItemContainerGenerator.ContainerFromItem((sender as
MenuItem).DataContext) as ListBoxItem;
       if (selectedListBoxItem == null)
       {
              return;
       }

       if (header == "Add Color")
       {
              selectedListBoxItem.Background = new SolidColorBrush(Colors.Red);
       }
       else
       {
              selectedListBoxItem.Background = new
SolidColorBrush(Colors.Black);
       }
       //To highlight the tapped item just use something like
selectedListBoxItem.Background = new SolidColorBrush(Colors.Green);
}




www.windowsphonegeek.com
                                                                                                 69
Silverlight for Windows Phone Toolkit in Depth




Step4. Build and run the project.

Here is how the result looks like:




www.windowsphonegeek.com
                                                 70
Silverlight for Windows Phone Toolkit in Depth




DatePicker
Overview
Basically, Windows Phone Toolkit`s DatePicker is an UI elements that will automatically provide
you with a TextBox input and when the user selects it, the picker will display a form where you
can choose another date using infinite scrolling. DatePicker is UX control that fits in the
Windows Phone Design Guidelines.




Getting Started
To begin using DatePicker first add a reference to the Microsoft.Phone.Controls.Toolkit.dll
assembly in your Windows Phone application project.

       NOTE: Microsoft.Phone.Controls.Toolkit.dll assembly is installed with the toolkit and you
       can find it in:
       For 32-bit systems:
       C:\Program Files\Microsoft SDKs\Windows
       Phone\v7.1\Toolkit\Aug11\Bin\Microsoft.Phone.Controls.Toolkit.dll
       For 64-bit systems:
       C:\Program Files (x86)\Microsoft SDKs\Windows
       Phone\v7.1\Toolkit\Aug11\Bin\Microsoft.Phone.Controls.Toolkit.dll

       Alternatively you can select it directly from the “...\Silverlight for Windows Phone Toolkit
       Source & Sample - Aug 2011\Bin\” if you have downloaded the “Silverlight for Windows
       Phone Toolkit Source & Sample - Aug 2011.zip” instead.


www.windowsphonegeek.com
                                                                                                      71
Silverlight for Windows Phone Toolkit in Depth




You can create an instance of the DatePicker control either in XAML or with C#/VB.

         Define an instance of the DatePicker control in XAML: you have to add the following
          namespace declaration:

xmlns:toolkit="clr-
namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"

XAML
<toolkit:DatePicker x:Name="datePicker" Value="2/3/2010"/>



         NOTE: Make sure that your page declaration includes the "toolkit" namespace! You can
         do this by using Visual Studio Toolbox, Expression Blend Designer or just include it on your
         own.

         Define an instance of the DatePicker control in C#/VB: just add the following using
          directive:

using Microsoft.Phone.Controls;

C#
DatePicker datePicker = new DatePicker();



         NOTE: If choosing to add this control via C# code then do not forget to associate it to a
         panel on your page for example: this.ContentPanel.Children.Add(datePicker);



IMPORTANT: To see the correct ApplicationBar icons in the DatePicker and TimePicker, you will
need to create a folder in the root of your project called "Toolkit.Content" and put the icons in
there. The toolkit provides the necessary icons, but you have to copy them from the
PhoneToolkitSample project. They must be named "ApplicationBar.Cancel.png" and
"ApplicationBar.Check.png", and the build action must be "Content"!




www.windowsphonegeek.com
                                                                                                        72
Silverlight for Windows Phone Toolkit in Depth




Key Properties

Header
Header is a dependency property of type object. It gets or sets the header of the control.
Example:
XAML

<toolkit:DatePicker x:Name="datePicker" Header="DatePicker"
Value="2/3/2010"/>




HeaderTemplate
HeaderTemplate is a dependency property of type DataTemplate. It gets or sets the template used to
display the control's header.


PickerPageUri
PickerPageUri is a dependency property of type Uri. It gets or sets the Uri to use for loading the
IDateTimePickerPage instance when the control is clicked. Check the "Customizing the full-
screen picker page" section below for more info and detailed example.




www.windowsphonegeek.com
                                                                                                     73
Silverlight for Windows Phone Toolkit in Depth




Value
Value is a dependency property of type “DateTime?”. It gets or sets the DateTime value.
Example:
XAML
<toolkit:DatePicker x:Name="datePicker" Value="2/3/2010"/>



ValueString
ValueString is a dependency property of type string. It gets the string representation of the
selected value.
Example:
C#
this.textBlock.Text = datePicker.ValueString;



ValueStringFormat
ValueStringFormat is a dependency property of type string. It gets or sets the format string to
use when converting the Value property to a string. For more information about the different
format strings you can visit the MSDN documentation.

       NOTE: Format strings include "{" and "}" so if you want to use them in XAML you have to
       escape the special characters. For example: ValueStringFormat="{}{0:d}" .



       NOTE: The default ValueStringFormat for DatePicker is "{}{0:d}" this means that in USA
       Culture this will appear as: 15/12/2010.



Key Events

ValueChanged
The ValueChanged event occurs when the Value property changes.
Example:




www.windowsphonegeek.com
                                                                                                  74
Silverlight for Windows Phone Toolkit in Depth




C#

this.datePicker.ValueChanged += new
EventHandler<DateTimeValueChangedEventArgs>(picker_ValueChanged);
//...

void picker_ValueChanged(object sender, DateTimeValueChangedEventArgs e)
{
       DateTime date = (DateTime)e.NewDateTime;
       this.textBlock.Text = date.ToString("d");
}




Customizing the full-screen picker page
You can customize the full-screen picker page by setting the DatePicker.PickerPageUri or
TimePicker.PickerPageUri property to point to a PhoneApplicationPage that implements the
IDateTimePickerPage interface. IDateTimePickerPage represents an interface for
DatePicker/TimePicker to use for communicating with a picker page. Basically it consists of only
one property:

C#

public interface IDateTimePickerPage
{
       /// <summary>
       /// Gets or sets the DateTime to show in the picker page and to set when
the user makes a selection.
       /// </summary>
       DateTime? Value
       {
              get;
              set;
       }
}



Let’s create a sample scenario with a custom page that resets the selected value of the
DatePicker to DateTime.Now. The steps for accomplishing this are as follows:

Step1. Add a sample Windows Phone Partial Page to your project and rename it to
"CustomPage".

Step2. In the code behind implement IDateTimePickerPage interface. The code is as follows:




www.windowsphonegeek.com
                                                                                                   75
Silverlight for Windows Phone Toolkit in Depth




C#

public partial class CustomPage : PhoneApplicationPage, IDateTimePickerPage
{
       public CustomPage()
       {
              InitializeComponent();
       }

       #region IDateTimePickerPage Members

       public DateTime? Value
       {
              get;
              set;
       }

       #endregion
}



Step3. After that add a button to the "CustomPage". The code is:

XAML

<Border BorderBrush="Red" Background="Orange" Height="200" Width="300">
       <Button Content="DateTime Now" x:Name="btn" Click="btn_Click"/>
</Border>



Step4. The next step is to add some code behind that will set the selected value of the
DatePicker to DateTime.Now. The code is:

C#

private void btn_Click(object sender, RoutedEventArgs e)
{
       // set date and close picker
       Value = DateTime.Now;
       NavigationService.GoBack();
}



Step5. Set the PickerPageUri to "/DatePickerDemo;component/CustomPage.xaml". the code is:

XAML

<toolkit:DatePicker x:Name="datePicker1" Header="Custom DatePicker"
Value="2/3/2010"
PickerPageUri="/DatePickerDemo;component/CustomPage.xaml" />




www.windowsphonegeek.com
                                                                                            76
Silverlight for Windows Phone Toolkit in Depth




Step6. Here is the result




That is all you need to do in order to have a custom full screen picker page. If you run the
example you will see that when you select the DatePicker our newly created "CustomPage"
page will appear. After that when you press the button NavigationService.GoBack(); is called
and the value of the DatePicker is updated with the current date time. Just so simply you can
implement your own custom full screen page and add whatever you prefer there.




www.windowsphonegeek.com
                                                                                                77
Silverlight for Windows Phone Toolkit in Depth




ExpanderView
Overview
Basically, ExpanderView is a control which displays a header and a collapsible drop-down. When
the user taps the header, the ExpanderView is expanded / collapsed. ExpanderView is in itself a
simple HeaderedItemsControl that exposes various additional properties and events for
controlling the expanding and collapsing functionality.




Getting Started
To begin using ExpanderView, first add a reference to the Microsoft.Phone.Controls.Toolkit.dll
assembly in your Windows Phone application project.

       NOTE: Microsoft.Phone.Controls.Toolkit.dll assembly is installed with the toolkit and you
       can find it in:
       For 32-bit systems:
       C:\Program Files\Microsoft SDKs\Windows
       Phone\v7.1\Toolkit\Aug11\Bin\Microsoft.Phone.Controls.Toolkit.dll
       For 64-bit systems:
       C:\Program Files (x86)\Microsoft SDKs\Windows
       Phone\v7.1\Toolkit\Aug11\Bin\Microsoft.Phone.Controls.Toolkit.dll

       Alternatively you can select it directly from the “...\Silverlight for Windows Phone Toolkit
       Source & Sample - Aug 2011\Bin\” if you have downloaded the “Silverlight for Windows
       Phone Toolkit Source & Sample - Aug 2011.zip” instead.




www.windowsphonegeek.com
                                                                                                      78
Silverlight for Windows Phone Toolkit in Depth



You can create an instance of the ExpanderView control either in XAML or with C#/VB.

         Define an instance of the ExpanderView control in XAML: you have to add the
          following namespace declaration:

xmlns:toolkit="clr-
namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"

XAML
<toolkit:ExpanderView Header="Expander Header" x:Name="expander">
       <toolkit:ExpanderView.Items>
              <TextBlock FontSize="40" Text="Expanded Content"/>
       </toolkit:ExpanderView.Items>
</toolkit:ExpanderView>



         NOTE: Make sure that your page declaration includes the "toolkit" namespace! You can
         do this by using VisualStudio Toolbox, Expression Blend Designer or just include it on your
         own.

         Define an instance of the ExpanderView control in C#: just add the following using
          directive:

using Microsoft.Phone.Controls;

C#

ExpanderView expander = new ExpanderView();
expander.Header = "Expander Header";
expander.Items.Add(new TextBlock() {Text = "Expanded Content"});




Key Properties
Expander
Expander is a dependency property of type object. It gets or sets the expander object.
Example:
XAML
<toolkit:ExpanderView Header="Expander Header" x:Name="expander">
   <toolkit:ExpanderView.Items>
       <TextBlock FontSize="40" Text="Expanded Content 1" Foreground="Orange"/>
       <TextBlock FontSize="40" Text="Expanded Content 2" Foreground="YellowGreen"/>
   </toolkit:ExpanderView.Items>
   <toolkit:ExpanderView.Expander>
       <Rectangle Height="100" Width="400" Fill="Green"/>
   </toolkit:ExpanderView.Expander>
</toolkit:ExpanderView>



www.windowsphonegeek.com
                                                                                                       79
Silverlight for Windows Phone Toolkit in Depth




ExpanderTemplate
Expander is a dependency property of type DataTemplate. It gets or sets the template used to
display the control's expander.

IsNonExpandable
IsNonExpandable is a dependency property of type bool. It gets or sets the flag that indicates
whether the Expander View is non-expandable.

NonExpandableHeader
NonExpandableHeader is a dependency property of type object. It gets or sets the header
object that is displayed when the Expander View is non-expandable.
Example:
XAML

<toolkit:ExpanderView Header="Expander Header" x:Name="expander"
NonExpandableHeader="Non Expander Header" IsNonExpandable="True">
       <toolkit:ExpanderView.Items>
              <TextBlock FontSize="40" Text="Expanded Content"/>
       </toolkit:ExpanderView.Items>
</toolkit:ExpanderView>




NonExpandableHeaderTemplate
NonExpandableHeaderTemplate is a dependency property of type DataTemplate. It gets or sets
the data template that defines the non-expandable header.


www.windowsphonegeek.com
                                                                                                 80
Silverlight for Windows Phone Toolkit in Depth




IsExpanded
IsExpanded is a dependency property of type bool. It gets or sets the flag that indicates
whether the Expander View is expanded.

HasItems
HasItems is a dependency property of type bool. It gets or sets the flag that indicates whether
the Expander View has items.



Key Events
Expanded
Occurs when the ExpanderView expands to display its content.
Example:
C#

expander.Expanded += new System.Windows.RoutedEventHandler(expander_Expanded);
//...
void expander_Expanded(object sender, System.Windows.RoutedEventArgs e)
{
       //...
}



Collapsed
Occurs when the ExpanderView collapses to hide its content.
Example:
C#

expander.Collapsed += new
System.Windows.RoutedEventHandler(expander_Collapsed);
//...
void expander_Collapsed(object sender, System.Windows.RoutedEventArgs e)
{
       //...
}




www.windowsphonegeek.com
                                                                                                  81
Silverlight for Windows Phone Toolkit in Depth




Data Binding ExpanderView
This example demonstrates how to populate the ExpanderView with data using data binding. We will
implement a sample expandable menu for a pizza company which shows different kinds of
pizzas in collapsed state and detailed descriptions of the ingredients in expanded state.

      Defining the Data Source
Here are the steps we will follow in order to create a data source:

Step1. Define the business/data class:

The first step is to define the data class. Let’s create a “CustomPizza" class which exposes the
following properties:

C#
public class CustomPizza : INotifyPropertyChanged
{
       private bool isExpanded;

       public string Image
       {
              get;
              set;
       }

       public string Name
       {
              get;
              set;
       }

       public DateTime DateAdded
       {
              get;
              set;
       }

       public IList<PizzaOption> Options
       {
              get;
              set;
       }

       public bool HasNoOptions
       {
              get
              {
                     return this.Options == null || this.Options.Count == 0;
              }
       }




www.windowsphonegeek.com
                                                                                                   82
Silverlight for Windows Phone Toolkit in Depth



       public bool IsExpanded
       {
              get
              {
                     return this.isExpanded;
              }
              set
              {
                     if (this.isExpanded != value)
                     {
                            this.isExpanded = value;
                            this.OnPropertyChanged("IsExpanded");
                     }
              }
       }

       public event PropertyChangedEventHandler PropertyChanged;

       protected void OnPropertyChanged(string propertyName)
       {
              PropertyChangedEventHandler handler = this.PropertyChanged;
              if (handler != null)
              {
                     handler(this, new PropertyChangedEventArgs(propertyName));
              }
       }
}

Where PizzaOption is the following class:
C#
public class PizzaOption
{
       public string Name
       {
              get;
              set;
       }
}


Step2. Create a new Images folder and add some images which will be shown in the expanders:

      NOTE: You will also have to add an Image folder with some images inside. For example :




www.windowsphonegeek.com
                                                                                               83
Silverlight for Windows Phone Toolkit in Depth




Step3. Create a sample collection with items of type CustomPizza:
C#
public MainPage()
{
  List<CustomPizza> customPizzas = new List<CustomPizza>()
   {
       new CustomPizza() { Name = "Custom Pizza 1",
       DateAdded = new DateTime(2010, 7, 8), Image="Images/pizza1.png",
       Options = new List<PizzaOption>
       {
              new PizzaOption() { Name = "Ham" },
              new PizzaOption() { Name = "Mushrooms" },
              new PizzaOption() { Name = "Tomatoes" }
       }},

        new CustomPizza() { Name = "Custom Pizza 2",
        DateAdded = new DateTime(2011, 2, 10),
        Image="Images/pizza2.png",
        Options = new List<PizzaOption>
        {
               new PizzaOption() { Name = "Ham" },
               new PizzaOption() { Name = "Olives" },
               new PizzaOption() { Name = "Mozzarella" }
        }},

        new CustomPizza() { Name = "Surprise Pizza",
        Image= null,
        DateAdded = new DateTime(2011, 4, 1),
        Options = null },

        new CustomPizza() { Name = "Custom Pizza 3",
        Image="Images/pizza3.png",
        DateAdded = new DateTime(2011, 5, 15),
        Options = new List<PizzaOption>
        {
               new PizzaOption() { Name = "Salami" },
               new PizzaOption() { Name = "Mushrooms" },
               new PizzaOption() { Name = "Onions" }
        }},

        new CustomPizza() { Name = "Custom Pizza 4",
        Image="Images/pizza4.png",
        DateAdded = new DateTime(2011, 7, 20),
        Options = new List<PizzaOption>
        {
               new PizzaOption() { Name = "Pepperoni" },
               new PizzaOption() { Name = "Olives" },
               new PizzaOption() { Name = "Mozzarella" }
        }},
     };
       //...
}




www.windowsphonegeek.com
                                                                          84
Silverlight for Windows Phone Toolkit in Depth




    Data bind ExpanderView
At first we will add the necessary DataTemplates in the page Resources section.

Step1. Define a RelativeTimeConverter in the page Resources. We will use it later to transform
the “AddedDate” value into suitable string (ex: 08/08/2011 can be transformed into “one
month ago”).
XAML
<phone:PhoneApplicationPage.Resources>
    <toolkit:RelativeTimeConverter x:Key="RelativeTimeConverter"/>
</phone:PhoneApplicationPage.Resources>


Step2. Define a custom HeaderTemplate in the page Resources.
XAML
<phone:PhoneApplicationPage.Resources>
    <DataTemplate x:Key="CustomHeaderTemplate">
                     <TextBlock Text="{Binding Name}"
                     FontSize="{StaticResource PhoneFontSizeExtraLarge}"
                     FontFamily="{StaticResource PhoneFontFamilySemiLight}"/>
    </DataTemplate>
</phone:PhoneApplicationPage.Resources>


Step3. Define a custom ExpanderTemplate in the page Resources.
XAML
<phone:PhoneApplicationPage.Resources>
   <DataTemplate x:Key="CustomExpanderTemplate">
       <StackPanel Orientation="Horizontal">
          <Image Source="{Binding Image}" Stretch="None"/>
          <TextBlock Foreground="{StaticResource PhoneSubtleBrush}"
FontSize="{StaticResource PhoneFontSizeNormal}" VerticalAlignment="Center">
              <TextBlock.Text>
                     <Binding Path="DateAdded" Converter="{StaticResource
RelativeTimeConverter}" StringFormat="Date added: {0}" />
              </TextBlock.Text>
         </TextBlock>
       </StackPanel>
   </DataTemplate>
</phone:PhoneApplicationPage.Resources>


Step4. Define a custom ItemTemplate in the page Resources.
XAML
<phone:PhoneApplicationPage.Resources>
       <DataTemplate x:Key="CustomItemTemplate">
                     <TextBlock Text="{Binding Name}" />
       </DataTemplate>
</phone:PhoneApplicationPage.Resources>




www.windowsphonegeek.com
                                                                                                 85
Silverlight for Windows Phone Toolkit in Depth




Step5. Define a custom NonExpandableHeaderTemplate in the page Resources.
XAML
<phone:PhoneApplicationPage.Resources>
   <DataTemplate x:Key="CustomNonExpandableHeaderTemplate">
       <StackPanel Orientation="Vertical">
          <TextBlock Text="{Binding Name}"
       FontSize="{StaticResource PhoneFontSizeExtraLarge}"
       FontFamily="{StaticResource PhoneFontFamilySemiLight}"/>
          <TextBlock Foreground="{StaticResource PhoneSubtleBrush}"
                   FontSize="{StaticResource PhoneFontSizeNormal}">
                <TextBlock.Text>
                     <Binding Path="DateAdded" Converter="{StaticResource
RelativeTimeConverter}" StringFormat="Date added: {0}" />
                </TextBlock.Text>
          </TextBlock>
          <TextBlock Text="The ingredients will be a surpise!"
Foreground="{StaticResource PhoneSubtleBrush}"
FontSize="{StaticResource PhoneFontSizeNormal}" />
       </StackPanel>
   </DataTemplate>
</phone:PhoneApplicationPage.Resources>



Step6. Add a ListBox in XAML which will be used to display the collection of CustomPizza
objects using ExpanderView controls. The ExpanderView and its binding to “CustomPizza”
properties is defined in the ItemTemplate. Here is how the ExpanderView should look like:

XAML
<ListBox Grid.Row="0" x:Name="listBox">
   <ListBox.ItemContainerStyle>
       <Style TargetType="ListBoxItem">
           <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
       </Style>
       </ListBox.ItemContainerStyle>
       <ListBox.ItemsPanel>
              <ItemsPanelTemplate>
                     <StackPanel/>
              </ItemsPanelTemplate>
       </ListBox.ItemsPanel>
       <ListBox.ItemTemplate>
              <DataTemplate>
                     <toolkit:ExpanderView Header="{Binding}"
Expander="{Binding}"
ItemsSource="{Binding Options}"
NonExpandableHeader="{Binding}"
IsNonExpandable="{Binding HasNoOptions}"
IsExpanded="{Binding IsExpanded, Mode=TwoWay}"
HeaderTemplate="{StaticResource CustomHeaderTemplate}"
ExpanderTemplate="{StaticResource CustomExpanderTemplate}"
ItemTemplate="{StaticResource CustomItemTemplate}"
NonExpandableHeaderTemplate="{StaticResource
CustomNonExpandableHeaderTemplate}"/>
              </DataTemplate>



www.windowsphonegeek.com
                                                                                            86
Silverlight for Windows Phone Toolkit in Depth



       </ListBox.ItemTemplate>
</ListBox>



Step7. Set the ListBox ItemsSource

C#
public MainPage()
{
    //...
    this.listBox.ItemsSource = customPizzas;
}



Here is how the final result should look like:
                                           Normal State:




                                           Expanded State:




www.windowsphonegeek.com
                                                             87
Silverlight for Windows Phone Toolkit in Depth




ExpandAll and CollapseAll Example
This example demonstrates how to expand/collapse all the ExpanderViews from the ListBox
defined in the previous example. Note that all ListBox items are ExpanderViews.
Step1. Add two buttons that will be used to Expand and Collapse all items:
XAML
<StackPanel Grid.Row="1" Orientation="Horizontal">
   <Button x:Name="btnExpand" Content="Expand All" Click="btnExpand_Click" />
   <Button x:Name="btnCollapse" Content="Collapse All" Click="btnCollapse_Click" />
</StackPanel>



Step2. Add the following helper method that will be used to expand/collapse the
ExpanderViews placed inside the ListBox control.

C#

private void SetExpanded(bool expand)
{
       foreach (object item in this.listBox.Items)
       {
              CustomPizza customPizza = item as CustomPizza;
              if (customPizza != null)
              {
                     customPizza.IsExpanded = expand;
              }
       }
}



Step3. Add the following code inside the “btnExpand” Click handler. (Expand all functionality)
C#
private void btnExpand_Click(object sender, RoutedEventArgs e)
{
       this.SetExpanded(true);
}



Step4. Add the following code inside the “btnCollapse” Click handler. (Collapse all functionality)
C#
private void btnCollapse_Click(object sender, RoutedEventArgs e)
{
       this.SetExpanded(false);
}




www.windowsphonegeek.com
                                                                                                     88
    Silverlight for Windows Phone Toolkit in Depth




    GestureService and GestureListener
    Overview
    Basically, touch gestures are the primary method for a user to interact with a Windows Phone,
    requiring a user-initiated movement with single or multiple fingers on a touch screen.
    Developers can implement gesture support in their application using either the Silverlight or
    XNA frameworks. Each framework offers unique ways to handle touch input to create
    compelling, interactive end user applications. In this chapter we will focus on Silverlight.
    The controls provided in the Windows Phone Developer tools are used as touch interaction
    elements and are properly sized for touch interaction. According to the UI Design and
    Interaction Guide, the supported Windows Phone gestures are:
                                                                             
   Single-touch:                                                                 Multi-touch:
    Tap                                   Touch and Hold                          Pinch and Stretch




    Double Tap                            Pan




    By default Silverlight for Windows Phone allows you to process touch input by using
    manipulation events. Manipulation events are supported on objects derived from UIElement
    and enable users to move and scale objects in response to touch and multi-touch input.


    www.windowsphonegeek.com
                                                                                                      89
Silverlight for Windows Phone Toolkit in Depth




      NOTE: Rotate transforms are not supported on Windows Phone.


The following manipulation events are supported in Silverlight for Windows Phone:
  ManipulationStarted: This event occurs when the user starts a direct manipulation by
     placing their finger or fingers on the screen.
  ManipulationDelta: This event occurs repeatedly while the user is moving their finger or
     fingers on the screen.
  ManipulationCompleted: This event occurs when the user removed their finger or
     fingers from the screen

      NOTE: You can also handle simple gestures such as tap, double-tap, and tap-and-hold by
      using mouse events.

Manipulation events can detect touch input but in order to determine any particular gesture
you need to write some custom code. Here is the place where you can use the newly added
GestureService class from the toolkit.
In the latest release of the Silverlight for Windows Phone Toolkit you can find
the GestureService which provides an event-driven model for handling gestures in an
application. The GestureService can be used by attaching a GestureListener to an element. At
that point the element can listen for the gestures that it supports, such as Tap, Hold, Pinch, Flick
and others.



What is GestureService?
Basically GestureService is a static class that has an attached property GestureListenerProperty
of type GestureListener.

      NOTE: SetGestureListener(…) is obsolete. Do not add handlers using this method. Instead,
      use GetGestureListener, which will create a new instance if one is not already set, to add
your handlers to an element.




www.windowsphonegeek.com
                                                                                                       90
Silverlight for Windows Phone Toolkit in Depth




What is GestureListener?
The GestureListener is a class that provides an easy way for you to detect touch gestures in
your application. It allows you to implement listeners for the following gestures:
      Double-tap
      DragStarted, DragDelta, and DragCompleted: Three events that can be used together
     to implement easy drag-and-drop on Windows Phone
      Flick
      Hold
      PinchStarted, PinchDelta, and PinchCompleted: Three events that can be used
     together to tell if a user is pinching something, typically to zoom in or out
      Tap


      NOTE: The Windows Phone Emulator does not support multitouch input through the
      mouse, so you must test scale transforms on a development computer that supports
      touch input, or test on an actual device.


Getting Started
To begin using GestureService/GestureListener first add a reference to the
Microsoft.Phone.Controls.Toolkit.dll assembly in your Windows Phone application project.

       NOTE: Microsoft.Phone.Controls.Toolkit.dll assembly is installed with the toolkit and you
       can find it in:
       For 32-bit systems:
       C:\Program Files\Microsoft SDKs\Windows
       Phone\v7.1\Toolkit\Aug11\Bin\Microsoft.Phone.Controls.Toolkit.dll
       For 64-bit systems:
       C:\Program Files (x86)\Microsoft SDKs\Windows
       Phone\v7.1\Toolkit\Aug11\Bin\Microsoft.Phone.Controls.Toolkit.dll

       Alternatively you can select it directly from the “...\Silverlight for Windows Phone Toolkit
       Source & Sample - Aug 2011\Bin\” if you have downloaded the “Silverlight for Windows
       Phone Toolkit Source & Sample - Aug 2011.zip” instead.


You can create GestureService/ GestureListener in XAML or C#/VB.




www.windowsphonegeek.com
                                                                                                      91
Silverlight for Windows Phone Toolkit in Depth




         Define GestureService/ GestureListener in XAML: you have to add the following
          namespace declaration (for example):

xmlns:toolkit="clr-
namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"

To associate GestureService/GestureListener to a rectangle (for example) you have to add the
following code:
C#

<Rectangle Fill="Orange" x:Name="rect">
       <toolkit:GestureService.GestureListener>
              <toolkit:GestureListener Tap="GestureListener_Tap" />
       </toolkit:GestureService.GestureListener>
</Rectangle>




         NOTE: Make sure that your page declaration includes the "toolkit" namespace! You can
         do this by using Visual Studio Toolbox, Expression Blend Designer or just include it on your
         own.

         Define GestureService/GestureListener in C#: just add the following using directive:

using Microsoft.Phone.Controls;

In order to associate GestureService /GestureListener to a rectangle (for example) you have to
add the following code:

C#
Rectangle rect;
// Constructor
public MainPage()
{
       InitializeComponent();
       this.rect = new Rectangle();
       rect.Height = 200;
       rect.Width = 200;
       rect.Fill = new SolidColorBrush(Colors.Red);
       this.ContentPanel.Children.Add(rect);

          var gl = GestureService.GetGestureListener(rect);
          gl.Tap += new EventHandler<GestureEventArgs>(GestureListener_Tap);
}

private void GestureListener_Tap(object sender, GestureEventArgs e)
{
       this.rect.Fill = new SolidColorBrush(Colors.White);
}




www.windowsphonegeek.com
                                                                                                        92
Silverlight for Windows Phone Toolkit in Depth




GestureListener Key Events
GestureBegin
The GestureBegin event. You can use it either in XAML or C#.
Example:
C#

GestureListener gestureListener = GestureService.GetGestureListener(rect);
gestureListener.GestureBegin += new
EventHandler<GestureEventArgs>(gestureListener_GestureBegin);

//…

void gestureListener_GestureBegin(object sender, GestureEventArgs e)
{
       //...
}



The base class for all gesture event arguments is GestureEventArgs. It exposes the following
properties and methods:

           OriginalSource
   This is the first hit-testable item under the touch point. Determined by a combination of
order in the tree and Z-order.

           Handled
          If an event handler sets this to true, it stops event bubbling.

           GetPosition(UIElement relativeTo)
      Returns the position of the gesture's starting point relative to a given UIElement.


GestureCompleted
The GestureCompleted event. You can use it either in XAML or C#.
Example:
C#

GestureListener gestureListener = GestureService.GetGestureListener(rect);
gestureListener.GestureCompleted += new
EventHandler<GestureEventArgs>(gestureListener_GestureCompleted);

//..




www.windowsphonegeek.com
                                                                                               93
Silverlight for Windows Phone Toolkit in Depth



void gestureListener_GestureCompleted(object sender, GestureEventArgs e)
{
       //...
}




Tap
The Tap event (touch, release, no movement). You can use it either in XAML or C#.
Example:
XAML

<Rectangle Fill="Orange" x:Name="rect">
       <toolkit:GestureService.GestureListener>
              <toolkit:GestureListener Tap="GestureListener_Tap" />
       </toolkit:GestureService.GestureListener>
</Rectangle>




C#

void GestureListener_Tap(object sender, GestureEventArgs e)
{
       //...
}




DoubleTap
The DoubleTap event is raised instead of Tap if the time between two taps is short enough. You
can use it either in XAML or C#.
Example:
C#

GestureListener gestureListener = GestureService.GetGestureListener(rect);
gestureListener.DoubleTap += new
EventHandler<GestureEventArgs>(GestureListener_DoubleTap);

//..

void GestureListener_DoubleTap(object sender, GestureEventArgs e)
{
       //...
}




www.windowsphonegeek.com
                                                                                                 94
Silverlight for Windows Phone Toolkit in Depth




Hold
The Hold event (touch and hold for one second). You can use it either in XAML or C#.
Example:
C#

GestureListener gestureListener = GestureService.GetGestureListener(rect);
gestureListener.Hold += new
EventHandler<GestureEventArgs>(GestureListener_Hold);

//..

void GestureListener_Hold(object sender, GestureEventArgs e)
{
       //...
}




DragStarted
The DragStarted event. You can use it either in XAML or C#.
Example:
C#

GestureListener gestureListener = GestureService.GetGestureListener(rect);
gestureListener.DragStarted += new
EventHandler<DragStartedGestureEventArgs>(gestureListener_DragStarted);

//..
void gestureListener_DragStarted(object sender, DragStartedGestureEventArgs e)
{
       //...
}



DragStartedGestureEventArgs is the type of the event arguments used in the DragStarted event
(derives from GestureEventArgs). So they have all methods and properties of the
GestureEventArgs plus one more:

        Direction
     The direction of the drag gesture, as determined by the initial drag change.




www.windowsphonegeek.com
                                                                                               95
Silverlight for Windows Phone Toolkit in Depth




DragDelta
The DragDelta event. You can use it either in XAML or C#.
Example:
C#

GestureListener gestureListener = GestureService.GetGestureListener(rect);
gestureListener.DragDelta += new
EventHandler<DragDeltaGestureEventArgs>(gestureListener_DragDelta);

//..

void gestureListener_DragDelta(object sender, DragDeltaGestureEventArgs e)
{
       //...
}



DragDeltaGestureEventArgs are the event args used by the DragDelta event (derives from
GestureEventArgs). They have all methods and properties of the GestureEventArgs plus:

        HorizontalChange
     The horizontal (X) change for this drag event.

        VerticalChange
     The vertical (Y) change for this drag event.

        Direction
     The direction of the drag gesture, as determined by the initial drag change.


DragCompleted
The DragCompleted event occurs on touch release after a drag, or when a second touch point is
added. You can use it either in XAML or C#.
Example:
C#

GestureListener gestureListener = GestureService.GetGestureListener(rect);
gestureListener.DragCompleted += new
EventHandler<DragCompletedGestureEventArgs>(gestureListener_DragCompleted);
//...
void gestureListener_DragCompleted(object sender, DragCompletedGestureEventArgs e)
{
       //...
}




www.windowsphonegeek.com
                                                                                                96
Silverlight for Windows Phone Toolkit in Depth




 DragCompletedGestureEventArgs are the event args used by the DragCompleted event
(derives from GestureEventArgs). They have all methods and properties of the
GestureEventArgs plus:

         HorizontalChange
     The total horizontal (X) change of the drag event.

         VerticalChange
     The total vertical (Y) change of the drag event.

         Direction
     The direction of the drag gesture, as determined by the initial drag change.

         HorizontalVelocity
     The final horizontal (X) velocity of the drag, if the drag was inertial.

         VerticalVelocity
      The final vertical (Y) velocity of the drag, if the drag was inertial.


Flick
The Flick event. Raised when a drag that was fast enough ends with a release. You can use it
either in XAML or C#.
Example:
C#

GestureListener gestureListener = GestureService.GetGestureListener(rect);
gestureListener.Flick += new
EventHandler<FlickGestureEventArgs>(gestureListener_Flick);
//..
void gestureListener_Flick(object sender, FlickGestureEventArgs e)
{
 //...
}


FlickGestureEventArgs are the event args used by the Flick event (derives from
GestureEventArgs). They have all methods and properties of the GestureEventArgs plus:

         HorizontalVelocity
      The horizontal (X) velocity of the flick.

       VerticalVelocity
     The vertical (Y) velocity of the flick.

         Angle
     The angle of the flick


www.windowsphonegeek.com
                                                                                               97
Silverlight for Windows Phone Toolkit in Depth



         Direction
      The direction of the flick gesture, as determined by the flick velocities.


PinchStarted
The PinchStarted event. You can use it either in XAML or C#.
Example:
C#

GestureListener gestureListener = GestureService.GetGestureListener(rect);
gestureListener.PinchStarted += new
EventHandler<PinchStartedGestureEventArgs>(gestureListener_PinchStarted);

//..

void gestureListener_PinchStarted(object sender, PinchStartedGestureEventArgs e)
{
       //...
}


 PinchStartedGestureEventArgs are the event args used by the PinchDelta and PinchCompleted
events (derives from MultiTouchGestureEventArgs). It exposes the following properties and
methods:

         Distance
      The distance between the two touch points.

         Angle
     The angle defined by the two touch points.


PinchDelta
Any two-touch point (two fingers) operation. You can use it either in XAML or C#.
Example:
C#

GestureListener gestureListener = GestureService.GetGestureListener(rect);
gestureListener.PinchDelta += new
EventHandler<PinchGestureEventArgs>(gestureListener_PinchDelta);
//..
void gestureListener_PinchDelta(object sender, PinchGestureEventArgs e)
{
       //...
}




www.windowsphonegeek.com
                                                                                             98
Silverlight for Windows Phone Toolkit in Depth




PinchGestureEventArgs are the event args used by the PinchDelta and PinchCompleted events.
This class exposes the following properties and methods:

        DistanceRatio
   Returns the ratio of the current distance between touch points / the original distance
between the touch points.

        TotalAngleDelta
    Returns the difference in angle between the current touch positions and the original touch
positions.



PinchCompleted
The end of a pinch operation. You can use it either in XAML or C#.
Example:
C#

GestureListener gestureListener = GestureService.GetGestureListener(rect);
gestureListener.PinchCompleted += new
EventHandler<PinchGestureEventArgs>(gestureListener_PinchCompleted);

//..

void gestureListener_PinchCompleted(object sender, PinchGestureEventArgs e)
{
       //...
}




Examples
Let’s say that we have an orange rectangle and want to change its color depending on the way
the user touches the screen. If the user Taps the screen then the color becomes White and if
Holds their finger over the rectangle its color becomes red.




www.windowsphonegeek.com
                                                                                                 99
Silverlight for Windows Phone Toolkit in Depth




Defining GestureService and GestureListener in XAML:

XAML

<Rectangle Fill="Orange" x:Name="rect">
       <toolkit:GestureService.GestureListener>
              <toolkit:GestureListener Tap="GestureListener_Tap"
Hold="GestureListener_Hold" />
       </toolkit:GestureService.GestureListener>
</Rectangle>



Add the following code in “GestureListener_Tap” and “GestureListener_Hold” handlers:

C#

private void GestureListener_Tap(object sender, GestureEventArgs e)
{
       this.rect.Fill = new SolidColorBrush(Colors.White);
}

private void GestureListener_Hold(object sender, GestureEventArgs e)
{
       this.rect.Fill = new SolidColorBrush(Colors.Red);
}



Alternatively you can attach the events programmatically in this way:

C#

var gl = GestureService.GetGestureListener(rect);
gl.Tap += new EventHandler<GestureEventArgs>(GestureListener_Tap);




       NOTE: SetGestureListener was deprecated, so instead you can use GetGestureListener.




www.windowsphonegeek.com
                                                                                             100
Silverlight for Windows Phone Toolkit in Depth




HubTile
Overview
Basically, the HubTile is a control that enables you to add animated and informative tiles to
your application. A HubTile can have Image, Title, Message and Notification. HubTiles can be
grouped using the GroupTag property. They are animated randomly using the following effects:

      Flip animation with PlaneProjection
      Translate animation




Getting Started
To begin using HubTile first add a reference to the Microsoft.Phone.Controls.Toolkit.dll
assembly in your Windows Phone application project.

       NOTE: Microsoft.Phone.Controls.Toolkit.dll assembly is installed with the toolkit and you
       can find it in:
       For 32-bit systems:
       C:\Program Files\Microsoft SDKs\Windows
       Phone\v7.1\Toolkit\Aug11\Bin\Microsoft.Phone.Controls.Toolkit.dll
       For 64-bit systems:
       C:\Program Files (x86)\Microsoft SDKs\Windows
       Phone\v7.1\Toolkit\Aug11\Bin\Microsoft.Phone.Controls.Toolkit.dll

       Alternatively you can select it directly from the “...\Silverlight for Windows Phone Toolkit
       Source & Sample - Aug 2011\Bin\” if you have downloaded the “Silverlight for Windows


www.windowsphonegeek.com
                                                                                                      101
Silverlight for Windows Phone Toolkit in Depth




          Phone Toolkit Source & Sample - Aug 2011.zip” instead.


      NOTE: The HubTileBackground color is determined by the PhoneAccentBrush. I.e. if your
      phone/emulator uses the Red theme which is the default one in Mango then your tiles will
be red.


      NOTE: HubTile is designed to fit in the Metro UI, so by default its size is hardcoded to be
      173x173 and cannot be changed simply by changing the Height/Width properties. So it is
not recommended to use other sizes. However if you really want to change the size the only way
to do this is by changing the whole Style with the ControlTemplate!

You can create an instance of the HubTile control either in XAML or with C#/VB.

         Define an instance of the HubTile control in XAML: you have to add the following
          namespace declaration:

xmlns:toolkit="clr-
namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"

XAML

<toolkit:HubTile Title="HubTile Title" Message="This is HubTile message!"
x:Name="hubTile"/>




         NOTE: Make sure that your page declaration includes the "toolkit" namespace! You can
         do this by using Visual Studio Toolbox, Expression Blend Designer or just include it on your
         own.

         Define an instance of the HubTile control in C#: just add the following using directive:

using Microsoft.Phone.Controls;

C#
HubTile hubTile = new HubTile();
hubTile.Message = "This is HubTile message!";
hubTile.Title = "HubTile Title";




www.windowsphonegeek.com
                                                                                                        102
Silverlight for Windows Phone Toolkit in Depth




Key Properties
Title
Title is a dependency property of type string. It gets or sets the title of the HubTile control.

Message
Message is a dependency property of type string. It gets or sets the message of the HubTile
control, displayed in small font.

Source
Source is a dependency property of type ImageSource. It gets or sets the image source of the
HubTile control.
Example:

XAML
<toolkit:HubTile x:Name="hubTile" Source="wpglogo.png" Title="HubTile Title"
Message="This is HubTile message!" />




DisplayNotification
DisplayNotification is a dependency property of type bool. It determines the flag for new
notifications.

Notification
Notification is a dependency property of type string. It gets or sets the notification alert of the
HubTile control, displayed in large font at the back of the tile.
Example:

XAML
<toolkit:HubTile Background="Green" Source="wpglogo.png" Title="HubTile Title"
Notification="Notification" />




www.windowsphonegeek.com
                                                                                                      103
Silverlight for Windows Phone Toolkit in Depth




                         You can also change the color of the tiles through the Background
                         property.




IsFrozen
IsFrozen is a dependency property of type bool. It gets or sets the corresponding flag for all
images which are not animated.

       NOTE: It is a good practice, from a performance point of view, to freeze the animation of
       your tiles when they are not visible! Use either the IsFrozen property,
       FreezeHubTile(HubTile tile) or FreezeGroup(string group) methods of HubTileService!


GroupTag
GroupTag is a dependency property of type string. It gets or sets the group tag of the HubTile
control. Usually when you have more than one HubTile you will want to group them, so that
you can freeze/unfreeze the whole group later.
Example:
XAML

<toolkit:HubTile Title="London" GroupTag="Cities"/>
<toolkit:HubTile Title="NewYork" GroupTag="Cities"/>




C#

HubTileService.FreezeGroup("Cities");
HubTileService.UnfreezeGroup("Cities");




HubTileService
Basically, the HubTileService allows you to control the animation of hub tiles. It exposes the
following static methods:




www.windowsphonegeek.com
                                                                                                   104
Silverlight for Windows Phone Toolkit in Depth




FreezeHubTile(HubTile tile)
Freeze a hub tile.

Example:
XAML

<toolkit:HubTile x:Name="hubTile" Title="HubTile Title" Message="Message"/>



C#

HubTileService.FreezeHubTile(this.hubTile);




UnfreezeHubTile(HubTile tile)
Unfreezes a hub tile and restarts the timer if needed.


FreezeGroup(string group)
Freezes all the hub tiles with the specified group tag that are not already frozen.

Example:

XAML

<toolkit:HubTile Title="London" GroupTag="Cities"/>
<toolkit:HubTile Title="NewYork" GroupTag="Cities"/>




C#

HubTileService.FreezeGroup("Cities");



UnfreezeGroup(string group)
Unfreezes all the hub tiles with the specified group tag that are currently frozen and restarts the timer if
needed.

Example:

XAML

<toolkit:HubTile Title="London" GroupTag="Cities"/>
<toolkit:HubTile Title="NewYork" GroupTag="Cities"/>




www.windowsphonegeek.com
                                                                                                               105
Silverlight for Windows Phone Toolkit in Depth




C#

HubTileService.UnfreezeGroup("Cities");




Data Binding HubTile
This example demonstrates how to populate the HubTile control with data using data binding.
We will implement a sample animated menu for a fast food company which shows: Title,
Description, Price, etc.

      Defining the Data Source
Here are the steps we will follow in order to create a data source:

Step1. Define the business/data class:

The first step is to define the data class. Let’s create a ”TileItem" class which exposes the
following properties:

C#
public class TileItem
{
       public string ImageUri
       {
              get;
              set;
       }

       public string Title
       {
              get;
              set;
       }

       public string Notification
       {
              get;
              set;
       }

       public bool DisplayNotification
       {
              get
              {
                     return !string.IsNullOrEmpty(this.Notification);
              }
       }

       public string Message


www.windowsphonegeek.com
                                                                                                106
Silverlight for Windows Phone Toolkit in Depth



       {
               get;
               set;
       }

       public string GroupTag
       {
              get;
              set;
       }
}



Step2. Create a new Images folder and add some images which will be shown in the HubTiles:

      NOTE: You will also have to add an Image folder with some images inside. For example :




Step3. Create a sample collection with items of type TileItem:

C#

public MainPage()
{
       InitializeComponent();

       List<TileItem> tileItems = new List<TileItem>()
       {
              new TileItem() {
                     ImageUri ="/Images/chicken.jpg",
                     Title = "Chicken", Notification = "$3.49", GroupTag = "TileGroup"
              },
              new TileItem() {
                     ImageUri ="/Images/wings.jpg",
                     Title = "Wings", Notification = "Only $2.49", GroupTag = "TileGroup"
              },
              new TileItem() {
                     ImageUri = "/Images/bonfillet.jpg",
                     Title = "Chicken\nFillet",
                     Message = "A couple of these will not hurt your diet."
              },
              new TileItem() {
                     ImageUri = "/Images/burger.jpg",



www.windowsphonegeek.com
                                                                                               107
Silverlight for Windows Phone Toolkit in Depth



                       Title = "Burger", Notification = "$3.99"
                },
                new TileItem() {
                       ImageUri = "/Images/bucket.jpg",
                       Title = "Chicken\nBucket", Notification = "$19.99"
                },
                new TileItem() {
                       ImageUri = "/Images/fries.jpg",
                       Title = "Fries", Notification = "Only $1.99"
                },
                new TileItem() {
                       ImageUri = "/Images/caesar.jpg",
                       Title = "Caesar Salad", Notification = "$4.99"
                },
                new TileItem() {
                       ImageUri = "/Images/corn.jpg",
                       Title = "Corn", Notification = "Only $1.99"
                },
        };
             //...
}



       Data binding the HubTile

Step1. Define HubTile in XAML.
We will add a ListBox which will be used to display a collection of TileItems using a HubTile
control for each. The HubTile and its binding to TileItem properties are defined in the
ItemTemplate. We will also change the ItemsPanel of the list box to WrapPanel so that its items
will be rendered appropriately. Here is how the code should look like:

XAML
<ListBox Grid.Row="0" x:Name="tileList">
       <ListBox.ItemsPanel>
              <ItemsPanelTemplate>
                     <toolkit:WrapPanel Orientation="Horizontal" />
              </ItemsPanelTemplate>
       </ListBox.ItemsPanel>
       <ListBox.ItemTemplate>
              <DataTemplate>
                     <toolkit:HubTile Title="{Binding Title}" Margin="3"
Notification="{Binding Notification}"
DisplayNotification="{Binding DisplayNotification}"
Message="{Binding Message}"
GroupTag="{Binding GroupTag}"
Source="{Binding ImageUri}">
                     </toolkit:HubTile>
              </DataTemplate>
       </ListBox.ItemTemplate>
</ListBox>




www.windowsphonegeek.com
                                                                                                  108
Silverlight for Windows Phone Toolkit in Depth




Step2. Populate the ListBox with data through its ItemsSource property:

C#

public MainPage()
{
       InitializeComponent();
       //...
       this.tileList.ItemsSource = tileItems;
}



Step3. Build the project and run it. Here is how the result should look like(in red and lime
themes):




Freezing and Unfreezing tiles
This example demonstrates how to freeze and unfreeze the data bound HubTile controls from
the previous example.

Step1. Add two buttons that will be used to Freeze and Unfreeze all tiles in the “TileGroup”:
XAML
<StackPanel Grid.Row="1" Orientation="Horizontal">
     <Button x:Name="btnFreeze" Content="Freeze 1st Row" Click="btnFreeze_Click" />
    <Button x:Name="btnUnfreeze" Content="Unfreeze 1st Row" Click="btnUnfreeze_Click" />
</StackPanel>




www.windowsphonegeek.com
                                                                                                109
Silverlight for Windows Phone Toolkit in Depth




Step2. Add the following code in the “btnFreeze” Click handler:

C#
private void btnFreeze_Click(object sender, RoutedEventArgs e)
{
       HubTileService.FreezeGroup("TileGroup");
}


Step3. Add the following code in the “btnUnfreeze” Click handler:

C#
private void btnUnfreeze_Click(object sender, RoutedEventArgs e)
{
       HubTileService.UnfreezeGroup("TileGroup");
}


Step4. Build the project and run it. Here is how the final result should look like:




www.windowsphonegeek.com
                                                                                      110
Silverlight for Windows Phone Toolkit in Depth




Now, when you tap the “Freeze 1st Row” button, the first two tiles (the tiles on the first row)
that have their GroupTag property set to “TileGroup” should stop animating. Alternatively, if
you tap the “Unfreeze 1st Row” button, the first two tiles should resume animating.




www.windowsphonegeek.com
                                                                                                  111
Silverlight for Windows Phone Toolkit in Depth




ListPicker
Overview
Basically, ListPicker is actually the Windows Phone equivalent of the ComboBox control. It
shows the selected item from a list and also allows the user to pick from a list if they want to
change it. ListPicker is a standard ItemsControl subclass with all the common elements of a
Selector, set of properties for customization and item display, data binding support.

ListPicker is not appropriate for displaying long lists of scrollable data. In such scenarios you
would better use a ListBox or the Windows Phone Toolkit's new LongListSelector. Use
ListPicker in scenarios where the user is offered a variety of different options and must select
one so that only the current value is displayed. The control implements two kinds of list
selection:

       In-place list selection
       Fullscreen popup for picking among more items




Getting Started
To begin using ListPicker first add a reference to the Microsoft.Phone.Controls.Toolkit.dll
assembly in your Windows Phone application project.

       NOTE: Microsoft.Phone.Controls.Toolkit.dll assembly is installed with the toolkit and you
       can find it in:
       For 32-bit systems:
       C:\Program Files\Microsoft SDKs\Windows
       Phone\v7.1\Toolkit\Aug11\Bin\Microsoft.Phone.Controls.Toolkit.dll


www.windowsphonegeek.com
                                                                                                    112
Silverlight for Windows Phone Toolkit in Depth




          For 64-bit systems:
          C:\Program Files (x86)\Microsoft SDKs\Windows
          Phone\v7.1\Toolkit\Aug11\Bin\Microsoft.Phone.Controls.Toolkit.dll

          Alternatively you can select it directly from the “...\Silverlight for Windows Phone Toolkit
          Source & Sample - Aug 2011\Bin\” if you have downloaded the “Silverlight for Windows
          Phone Toolkit Source & Sample - Aug 2011.zip” instead.

You can create an instance of the ListPicker control either in XAML or with C#/VB.

         Define a ListPicker instance in XAML: you have to add the following namespace
          declaration (for example):

xmlns:toolkit="clr-
namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"

XAML

<toolkit:ListPicker>
       <toolkit:ListPickerItem Content="Item1"/>
       <toolkit:ListPickerItem Content="Item2"/>
       <toolkit:ListPickerItem Content="Item3"/>
</toolkit:ListPicker>




         NOTE: Make sure that your page declaration includes the "toolkit" namespace! You can
         do this by using Visual Studio Toolbox, Expression Blend Designer or just include it on your
         own.

         Define a ListPicker instance in C#: just add the following using directive:

using Microsoft.Phone.Controls;

C#

ListPicker listPicker = new ListPicker();
ListPickerItem item1 = new ListPickerItem() { Content = "Item1" };
ListPickerItem item2 = new ListPickerItem() { Content = "Item2" };
ListPickerItem item3 = new ListPickerItem() { Content = "Item3" };
listPicker.Items.Add(item1);
listPicker.Items.Add(item2);
listPicker.Items.Add(item3);
this.ContentPanel.Children.Add(listPicker);




www.windowsphonegeek.com
                                                                                                         113
Silverlight for Windows Phone Toolkit in Depth




       NOTE: If choosing to add this control via C# code then do not forget to associate it to a
       panel on your page for example: this.ContentPanel.Children.Add(listPicker);



Key Properties
ListPickerMode
ListPickerMode is a dependency property of type ListPickerMode. It is used to determine the
current mode:
   Normal (this is the default value): only the selected item is visible on the original page.
   Expanded: all items are visible on the original page.
   Full: all items are visible in a separate Popup.



ItemCountThreshold
ItemCountThreshold is a read only dependency property of type int. It specifies the maximum
number of items that will be displayed in Expanded mode. The default value is 5. I.e. lists with
five or fewer items expand in-place while lists with more items switch to a full-screen selection
interface.


FullModeItemTemplate
FullModeItemTemplate is a dependency property of type DataTemplate. It is used to display
each item when ListPickerMode is set to Full.
Example:
XAML

<phone:PhoneApplicationPage.Resources>
       <DataTemplate x:Name="PickerFullModeItemTemplate">
              <StackPanel Orientation="Horizontal" Margin="16 21 0 20">
                     <TextBlock Text="{Binding Name}" Margin="16 0 0 0"
FontSize="43" FontFamily="{StaticResource PhoneFontFamilyLight}"/>
                     <TextBlock Text="language: "/>
                     <TextBlock Text="{Binding Language}" Foreground="Green"/>
              </StackPanel>
       </DataTemplate>
</phone:PhoneApplicationPage.Resources>




www.windowsphonegeek.com
                                                                                                    114
Silverlight for Windows Phone Toolkit in Depth




XAML

<toolkit:ListPicker x:Name="listPicker" ItemTemplate="{StaticResource
PickerItemTemplate}" SelectedIndex="2"
FullModeItemTemplate="{StaticResource PickerFullModeItemTemplate}"
FullModeHeader="Cities" CacheMode="BitmapCache"/>




FullModeHeader
FullModeItemTemplate is a dependency property of type object. It gets or sets the header to
use when ListPickerMode is set to Full.
Example:
XAML

<toolkit:ListPicker x:Name="listPicker" ItemTemplate="{StaticResource
PickerItemTemplate}" SelectedIndex="2"
FullModeItemTemplate="{StaticResource PickerFullModeItemTemplate}"
FullModeHeader="Cities" CacheMode="BitmapCache"/>




SelectedItem
SelectedItem gets or sets the selected item. ListPicker can be used with two-way bindings as
well. In such scenarios SelectedIndex/SelectedItem properties can be used to set the initial
value based on a data model. You can also use them in case you want the model to be updated
directly when selection changes.


SelectedIndex
SelectedIndex gets or sets the index of the selected item.
Example:
XAML

<toolkit:ListPicker x:Name="listPicker" ItemTemplate="{StaticResource
PickerItemTemplate}" SelectedIndex="2"
FullModeItemTemplate="{StaticResource PickerFullModeItemTemplate}"
FullModeHeader="Cities" CacheMode="BitmapCache"/>



Header
Header is a dependency property of type object. Gets or sets the header of the control.




www.windowsphonegeek.com
                                                                                               115
Silverlight for Windows Phone Toolkit in Depth




Example:
XAML

<toolkit:ListPicker x:Name="listPicker" ItemTemplate="{StaticResource
PickerItemTemplate}" Header="Cities" FullModeItemTemplate="{StaticResource
PickerFullModeItemTemplate}"   FullModeHeader="Cities" SelectedIndex="2"
CacheMode="BitmapCache"/>




HeaderTemplate
HeaderTemplate is a dependency property of type DataTemplate. Gets or sets the template
used to display the control's header.


PickerPageUri
PickerPageUri is a dependency property of type Uri. It gets or sets the Uri to use for loading the
ListPickerPage instance when the control is tapped.


ExpansionMode
ExpansionMode is a dependency property of type ExpansionMode. It gets or sets how the list
picker expands when tapped: ExpansionAllowed or FullScreenOnly. This property has an effect
only when SelectionMode is Single. When SelectionMode is Multiple, the ExpansionMode will
be treated as FullScreenOnly. ExpansionAllowed will only expand when the number of items is
less than or equal to ItemCountThreshold.


SelectionMode
SelectionMode is a dependency property of type SelectionMode. It determines the Selection
Mode: Single, Multiple or Extended.


SelectedItems
SelectedItems is a dependency property of type IList. It gets the selected items.




www.windowsphonegeek.com
                                                                                                     116
Silverlight for Windows Phone Toolkit in Depth




Key Events & Methods
SelectionChanged
Occurs when the selection changes.
C#

this.listPicker.SelectionChanged += new
SelectionChangedEventHandler(listPicker_SelectionChanged);

//...

void listPicker_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
       //...
}




public bool Open()
Opens the picker for selection either into Expanded or Full mode depending on the picker's
state.


Data Binding ListPicker
This example demonstrates how to populate ListPicker with data using data binding.
Step1. Define the business/data class:
C#
public class Cities
{
       public string Name
       {
              get;
              set;
       }

        public string Country
        {
               get;
               set;
        }

        public string Language
        {
               get;
               set;
        }
}


www.windowsphonegeek.com
                                                                                             117
Silverlight for Windows Phone Toolkit in Depth




Step2. Create a sample collection with items of type Cities:

C#

List<Cities> source = new List<Cities>();
source.Add(new Cities(){Name = "Madrid",Country ="ES",Language="Spanish"});
source.Add(new Cities(){Name = "Las Vegas",Country="US",Language="English"});
source.Add(new Cities(){Name = "London",Country="UK",Language="English"});
source.Add(new Cities(){Name = "Mexico", Country="MX",Language="Spanish"});



Step3. Set the newly created collection as ItemsSource of the ListPicker control:

C#
this.listPicker.ItemsSource = source;



Step4. Add the following DataTemplates into the Resources section of your page:
    PickerItemTemplate: will represent the actual ItemTemplate
    PickerFullModeItemTemplate: will represent the full mode ItemTemplate


XAML

<phone:PhoneApplicationPage.Resources>
       <DataTemplate x:Name="PickerItemTemplate">
              <StackPanel Orientation="Horizontal">
                     <Border Background="LightGreen" Width="34" Height="34">
                            <TextBlock Text="{Binding Country}" FontSize="16"
HorizontalAlignment="Center" VerticalAlignment="Center"/>
                     </Border>
                     <TextBlock Text="{Binding Name}" Margin="12 0 0 0"/>
              </StackPanel>
       </DataTemplate>
       <DataTemplate x:Name="PickerFullModeItemTemplate">
              <StackPanel Orientation="Horizontal" Margin="16 21 0 20">
                     <TextBlock Text="{Binding Name}" Margin="16 0 0 0"
FontSize="43" FontFamily="{StaticResource PhoneFontFamilyLight}"/>
                     <TextBlock Text="language: "/>
                     <TextBlock Text="{Binding Language}" Foreground="Green"/>
              </StackPanel>
       </DataTemplate>
</phone:PhoneApplicationPage.Resources>



Step5. Add the newly created DataTemplates to the ListPicker control:




www.windowsphonegeek.com
                                                                                    118
Silverlight for Windows Phone Toolkit in Depth




XAML

<toolkit:ListPicker x:Name="listPicker"
ItemTemplate="{StaticResource PickerItemTemplate}"
FullModeItemTemplate="{StaticResource PickerFullModeItemTemplate}"
Header="Cities" FullModeHeader="Cities" CacheMode="BitmapCache"/>




Step6. Here is how the final result looks like:




This is the typical way to populate this control with data and add some custom templates.


       NOTE: The given example demonstrates the usage of two separate custom templates for
       each of the states (ItemTemplate and FullModeItemTemplate).

If you do not want to have custom templates then you can use a simple list of strings with the
default ones. As a result the ListPicker gets displayed like this (in normal and expanded forms):
XAML
<toolkit:ListPicker Header="Default" Grid.Row="1" x:Name="defaultPicker"/>




C#

this.defaultPicker.ItemsSource = new List<string>() {"Madrid",
"London","Mexico" };




www.windowsphonegeek.com
                                                                                                    119
Silverlight for Windows Phone Toolkit in Depth




Working with ListPicker SelectedItem
Generally ListPicker is a kind of ItemControl together with ListBox and other similar controls.
This means that the basic structure is the same as well as the SelectedItem behavior.
When populating a ListPicker with items you have two options:
      Option1 - You can use ListPickerItems
      Option2 - Data Binding


When using Option1 the SelectedItem is actually a ListPickerItems so it is easy to perform the
desired manipulations.
However when using Option2 (which is actually 90% of the cases) the SelectedItem is of the
type of the business object (data class) which you used when performing data binding.




www.windowsphonegeek.com
                                                                                                  120
Silverlight for Windows Phone Toolkit in Depth




 Let’s say that we have a sample data bound ListPicker where SampleData is our business object
(data class):
C#

public class SampleData
{
       public string Day
       {
              get;
              set;
       }

       public string Temperature
       {
              get;
              set;
       }

       public int Number
       {
              get;
              set;
       }
}


The ListPicker is defined in XAML with the following DataTemplates:
XAML

<toolkit:ListPicker x:Name="listPicker" Header="Weekly Temperatures" >
   <toolkit:ListPicker.ItemTemplate>
     <DataTemplate>
       <StackPanel Orientation="Horizontal">
         <Border Background="YellowGreen" Width="50" Height="50" Margin="5">
           <TextBlock Text="{Binding Number}" FontSize="30"
HorizontalAlignment="Center"/>
         </Border>
         <TextBlock Text="{Binding Day}" Width="150" />
       </StackPanel>
     </DataTemplate>
   </toolkit:ListPicker.ItemTemplate>
   <toolkit:ListPicker.FullModeItemTemplate>
      <DataTemplate>
         <StackPanel Orientation="Horizontal">
            <TextBlock Text="{Binding Day}" Width="150"/>
            <TextBlock Text="{Binding Temperature}" Width="50"/>
            <Button Click="Button_Click" Content="Button" Margin="0,-10,0,0"/>
         </StackPanel>
       </DataTemplate>
   </toolkit:ListPicker.FullModeItemTemplate>
</toolkit:ListPicker>




www.windowsphonegeek.com
                                                                                                 121
Silverlight for Windows Phone Toolkit in Depth




Finally “listPicker” is populated with the following data source via its ItemSource property:
C#

List<SampleData> dataSource = new List<SampleData>();
dataSource.Add(new SampleData() { Day = "Sunday", Number=1, Temperature = "24 C" });
dataSource.Add(new SampleData() { Day = "Monday", Number = 2, Temperature = "18 C" });
dataSource.Add(new SampleData() { Day = "Tuesday", Number = 3, Temperature = "11 C" });
dataSource.Add(new SampleData() { Day = "Thirsday", Number = 4, Temperature = "15 C"
});
dataSource.Add(new SampleData() { Day = "Wednesday", Number = 5, Temperature = "22 C"
});
dataSource.Add(new SampleData() { Day = "Friday", Number = 6, Temperature = "22 C" });
dataSource.Add(new SampleData() { Day = "Saturday", Number = 7, Temperature = "21 C"
});
this.listPicker.ItemsSource = dataSource;




The final result looks like in this way:




How to access the Selected ListPickerItem when having data bound ListPicker?
In order to get the selected ListPickerItem all you need to do is the following:

C#

private void btnGetSelectedItem_Click(object sender, RoutedEventArgs e)
{
       ListPickerItem selectedItem =
this.listPicker.ItemContainerGenerator.ContainerFromItem(this.listPicker.SelectedItem) as
ListPickerItem;
}




www.windowsphonegeek.com
                                                                                                122
Silverlight for Windows Phone Toolkit in Depth




How to access the SelectedItem from a ListPicker event handler? (when having a
data bound ListPicker )
Let’s say that we have subscribed to the ListPicker SelectionChanged event. First we will get a
reference to the current SelectedItem data object and after that we will get a reference to the
SelectedItem container which is of type ListPickerItem.

C#

private void listPicker_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
       //Get the data object that represents the current selected item
       SampleData data = (sender as ListPicker).SelectedItem as SampleData;

       //Get the selected ListPickerItem container instance
       ListPickerItem selectedItem =
this.listPicker.ItemContainerGenerator.ContainerFromItem(data) as ListPickerItem;
}




How to access the SelectedItem from a control placed inside ListPicker
ItemTemplate/FullModeItemTemplate?
In this case we will add a Button inside the ListPicker FullModeItemTemplate and will subscribe
to its Click event. As you can see below you can get a reference to the SelectedItem data object
through the DataContext and after that you can use this data object to get a reference to the
Selected ListPickerItem :

C#

private void Button_Click(object sender, RoutedEventArgs e)
{
       SampleData data = (sender as Button).DataContext as SampleData;
       ListPickerItem pressedItem =
this.listPicker.ItemContainerGenerator.ContainerFromItem(data) as ListPickerItem;
       if (pressedItem != null)
       {
              //do something
       }
}




www.windowsphonegeek.com
                                                                                                   123
Silverlight for Windows Phone Toolkit in Depth




How to set the SelectedItem when having data bound ListPicker?
The easiest way to set the SelectedItem of a ListPicker is to use its SelectedIndex property:

C#

private void btnSetSelectedIndex_Click(object sender, RoutedEventArgs e)
{
       this.listPicker.SelectedIndex = 1;
}




      NOTE: SelectedIndex = 1 means the second item!



How to access the Selected ListPickerItem and its data if I know the
SelectedIndex? (When having data bound ListPicker)
In this case, first we will get a reference to the selected ListPickerItem using
ItemContainerGenerator.ContainerFromIndex and after that we will get the real data through
the DataContext:

C#

private void btnSelectedIndex_Click(object sender, RoutedEventArgs e)
{
       ListPickerItem selectedItem =
this.listPicker.ItemContainerGenerator.ContainerFromIndex(2) as ListPickerItem;
       SampleData data = selectedItem.DataContext as SampleData;
}




      NOTE: In some cases if you need to reference the selected item before the ListPicker is
      initialized you will have to use a Dispatcher.


Example:
C#

Dispatcher.BeginInvoke(() =>{
       ListPickerItem selectedItem =
       this.listPicker.ItemContainerGenerator.ContainerFromIndex(2) as
ListPickerItem; });




www.windowsphonegeek.com
                                                                                                124
Silverlight for Windows Phone Toolkit in Depth




LockablePivot
Overview
Basically, LockablePivot control adds a special mode to the Pivot control where only the current item
is shown (locked). It is suitable in cases when you have multiple selection, sliding, drawing, etc.

Getting Started
To begin using LockablePivot first add a reference to the Microsoft.Phone.Controls.Toolkit.dll
assembly in your Windows Phone application project.

        NOTE: Microsoft.Phone.Controls.Toolkit.dll assembly is installed with the toolkit and you
        can find it in:
        For 32-bit systems:
        C:\Program Files\Microsoft SDKs\Windows
        Phone\v7.1\Toolkit\Aug11\Bin\Microsoft.Phone.Controls.Toolkit.dll
        For 64-bit systems:
        C:\Program Files (x86)\Microsoft SDKs\Windows
        Phone\v7.1\Toolkit\Aug11\Bin\Microsoft.Phone.Controls.Toolkit.dll

        Alternatively you can select it directly from the “...\Silverlight for Windows Phone Toolkit
        Source & Sample - Aug 2011\Bin\” if you have downloaded the “Silverlight for Windows
        Phone Toolkit Source & Sample - Aug 2011.zip” instead.

You can create an instance of the LockablePivot control either in XAML or with C#/VB.

       Define an instance of the LockablePivot control in XAML: you have to add the
        following namespace declaration:

xmlns:toolkit="clr-
namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"

XAML
<toolkit:LockablePivot x:Name="pivot">
       <controls:PivotItem Header="Home">
         <!--...-->
       </controls:PivotItem>
</toolkit:LockablePivot>




www.windowsphonegeek.com
                                                                                                        125
Silverlight for Windows Phone Toolkit in Depth




         NOTE: Make sure that your page declaration includes the "toolkit" namespace! You can
         do this by using Visual Studio Toolbox, Expression Blend Designer or just include it on your
         own.


         NOTE: PivotItem is placed inside “Microsoft.Phone.Controls” so you will need to add a
         reference to “Microsoft.Phone.Controls.dll” and after that include the following
         namespace in XAML: xmlns:controls="clr-
namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls"



         Define an instance of the LockablePivot control in C#: just add the following using
          directive:

using Microsoft.Phone.Controls;

C#
LockablePivot pivot = new LockablePivot();
pivot.Items.Add(new PivotItem() { Header = "Home"});




Key Properties
LockablePivot is in fact a simple control that derives from Pivot, so it exposes all the properties
of the Pivot plus one more additional IsLocked property. For more information take a look at
the Pivot MSDN Documentation.


IsLocked
IsLocked is a property of type bool. It gets or sets the navigation lock mode of the
LockablePivot.



Example
This example demonstrates how to implement a simple drawing application using the
LockablePivot control as drawing surface. Here are the steps you will need to follow:

Step1. Define an instance of the LockablePivot control in XAML and add the code below inside
its items. The most important part here is the drawing canvas. You will also have to subscribe to
its MouseMove and MouseLeftButtonDown events.


www.windowsphonegeek.com
                                                                                                        126
Silverlight for Windows Phone Toolkit in Depth




XAML
<toolkit:LockablePivot x:Name="pivot">
       <controls:PivotItem Header="Home">
              <TextBlock Text="Welcome to My Drawing App!" FontSize="60"
Foreground="YellowGreen" TextWrapping="Wrap"/>
       </controls:PivotItem>
       <controls:PivotItem Header="Drawing">
              <StackPanel>
                     <Button Content="Lock Pivot" Click="btnLock_Click"/>
                     <TextBlock Text="Drawing area here:"/>
                     <Canvas x:Name="ContentPanelCanvas" Background="LightGray"
Height="300" Width="480" MouseMove="ContentPanelCanvas_MouseMove"
MouseLeftButtonDown="ContentPanelCanvas_MouseLeftButtonDown"/>
                     <Button Content="UnLock Pivot" Click="btnUnLock_Click"/>
              </StackPanel>
       </controls:PivotItem>
</toolkit:LockablePivot>




       NOTE: PivotItem is placed inside “Microsoft.Phone.Controls” so you will need to add a
       reference to “Microsoft.Phone.Controls.dll” and after that include the following
       namespace in XAML: xmlns:controls="clr-
namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls"

Step2. Define the drawing logic in MouseMove and MouseLeftButtonDown handlers of the
drawing Canvas.

C#
public partial class MainPage : PhoneApplicationPage
{
       private Point currentPoint;
       private Point oldPoint;

        public MainPage()
        {
               InitializeComponent();
        }

       private void ContentPanelCanvas_MouseMove(object sender, MouseEventArgs e)
       {
              currentPoint = e.GetPosition(this.ContentPanelCanvas);
              Line line = new Line() { X1 = currentPoint.X, Y1 = currentPoint.Y, X2
= oldPoint.X, Y2 = oldPoint.Y };
              line.Stroke = new SolidColorBrush(Colors.Red);
              line.StrokeThickness = 15;

               this.ContentPanelCanvas.Children.Add(line);
               oldPoint = currentPoint;
        }

       private void ContentPanelCanvas_MouseLeftButtonDown(object sender,
MouseButtonEventArgs e)



www.windowsphonegeek.com
                                                                                               127
Silverlight for Windows Phone Toolkit in Depth



        {
               currentPoint = e.GetPosition(ContentPanelCanvas);
               oldPoint = currentPoint;
        }
//...
}

Step3. Add the following code in, to Lock/Unlock the pivot.

XAML
private void btnLock_Click(object sender, RoutedEventArgs e)
{
       this.pivot.IsLocked = true;
}

private void btnUnLock_Click(object sender, RoutedEventArgs e)
{
       this.pivot.IsLocked = false;
}



Step4. Here is the result:




www.windowsphonegeek.com
                                                                   128
Silverlight for Windows Phone Toolkit in Depth




As you can see every time when you want to draw on the drawing canvas you can press “Lock
Pivot” to lock the current pivot item. When the drawing is ready you can press “Unlock Pivot”
button to unlock the pivot item and navigate to the next/previous one.




www.windowsphonegeek.com
                                                                                                129
Silverlight for Windows Phone Toolkit in Depth




LoopingSelector
Overview
Basically, LoopingSelector enables users to implement various looping scenarios in an easy way.
Basically it is an infinite list selector which contains all the functionality for a looping control, all
we need to do in order to use this component is just to provide an appropriate data source. We
can create a suitable data source by implementing the ILoopingSelectorDataSource interface. In
this article I will implement a numeric up down scenario using a simple numeric data source.




Getting Started
To begin using LongListSelector first add a reference to the
Microsoft.Phone.Controls.Toolkit.dll assembly in your Windows Phone application project.

        NOTE: Microsoft.Phone.Controls.Toolkit.dll assembly is installed with the toolkit and you
        can find it in:
        For 32-bit systems:
        C:\Program Files\Microsoft SDKs\Windows
        Phone\v7.1\Toolkit\Aug11\Bin\Microsoft.Phone.Controls.Toolkit.dll
        For 64-bit systems:
        C:\Program Files (x86)\Microsoft SDKs\Windows
        Phone\v7.1\Toolkit\Aug11\Bin\Microsoft.Phone.Controls.Toolkit.dll




www.windowsphonegeek.com
                                                                                                            130
Silverlight for Windows Phone Toolkit in Depth




          Alternatively you can select it directly from the “...\Silverlight for Windows Phone Toolkit
          Source & Sample - Aug 2011\Bin\” if you have downloaded the “Silverlight for Windows
          Phone Toolkit Source & Sample - Aug 2011.zip” instead.

You can create an instance of the LoopingSelector control either in XAML or with C#/VB.

         Define LongListSelector instance in XAML: you have to add the following namespace
          declaration (for example):

         NOTE: LoopingSelector is in the Microsoft.Phone.Controls.Primitives namespace.



XAML

<toolkit:LoopingSelector x:Name="selector" ItemMargin="2,3,3,2"
ItemSize="100,100"/>




C#

this.selector.DataSource = new IntLoopingDataSource();
//IntLoopingDataSource is a sample datasource. Detailed example is given
below!




         NOTE: Make sure that your page declaration includes the "toolkit" namespace! You can
         do this by using Visual Studio Toolbox, Expression Blend Designer or just include it on your
         own.

         Define LongListSelector instance in C#: just add the following using directive:

using Microsoft.Phone.Controls.Primitives;

C#

LoopingSelector selector = new LoopingSelector();
this.selector.DataSource = new IntLoopingDataSource();
//IntLoopingDataSource is a sample datasource. Detailed example is given
below!




www.windowsphonegeek.com
                                                                                                         131
Silverlight for Windows Phone Toolkit in Depth




This example demonstrates how to populate a LoopingSelector control in the easiest way using
a numeric data source and the default built-in ItemTemplate. We will divide the data source
into two pieces: LoopingDataSourceBase and IntLoopingDataSource.

        LoopingDataSourceBase
First we will create an abstract class: LoopingDataSourceBase that implements the
ILoopingSelectorDataSource interface. The purpose of this abstraction is to put all reusable
code in a base class so that this will allow us to concentrate on the specifics (any specific logic
for a particular data source) when implementing deriving looping data source classes. In our
case we will put the selection logic in an abstract base class. The code is as follows:

C#

// abstract the reusable code in a base class
// this will allow us to concentrate on the specifics when implementing
deriving looping data source classes
public abstract class LoopingDataSourceBase : ILoopingSelectorDataSource
{
       private object selectedItem;

         #region ILoopingSelectorDataSource Members

         public abstract object GetNext(object relativeTo);

         public abstract object GetPrevious(object relativeTo);

       public object SelectedItem
       {
              get
              {
                     return this.selectedItem;
              }
              set
              {
                     // this will use the Equals method if it is overridden for
the data source item class
                     if (!object.Equals(this.selectedItem, value))
                     {
                            // save the previously selected item so that we can
use it
                            // to construct the event arguments for the
SelectionChanged event
                            object previousSelectedItem = this.selectedItem;
                            this.selectedItem = value;
                            // fire the SelectionChanged event
                            this.OnSelectionChanged(previousSelectedItem,
this.selectedItem);
                     }
              }
       }



www.windowsphonegeek.com
                                                                                                      132
Silverlight for Windows Phone Toolkit in Depth




         public event EventHandler<SelectionChangedEventArgs> SelectionChanged;

       protected virtual void OnSelectionChanged(object oldSelectedItem, object
newSelectedItem)
       {
              EventHandler<SelectionChangedEventArgs> handler =
this.SelectionChanged;
              if (handler != null)
              {
                     handler(this, new SelectionChangedEventArgs(new object[] {
oldSelectedItem }, new object[] { newSelectedItem }));
              }
       }

         #endregion
}




      NOTE: ILoopingSelectorDataSource is the most important part when using
      LoopingSelector control. In order to fit in the data source requirements each data source
      class should implement ILoopingSelectorDataSource (implementing
ILoopingSelectorDataSource is expected by the LoopingSelector!).


        IntLoopingDataSource
After we have defined the abstract class it is time for the numeric data source implementation.
We will create an IntLoopingDataSource class which derives from our LoopingDataSourceBase
class. The class will represent a simple numeric up down looping of int values. The code is as
follows:

C#

public class IntLoopingDataSource : LoopingDataSourceBase
{
       private int minValue;
       private int maxValue;
       private int increment;

         public IntLoopingDataSource()
         {
                this.MaxValue = 10;
                this.MinValue = 0;
                this.Increment = 1;
                this.SelectedItem = 0;
         }

         public int MinValue
         {


www.windowsphonegeek.com
                                                                                                  133
Silverlight for Windows Phone Toolkit in Depth



               get
               {
                       return this.minValue;
               }
               set
               {
                     if (value >= this.MaxValue)
                     {
                            throw new ArgumentOutOfRangeException("MinValue",
"MinValue cannot be equal or greater than MaxValue");
                     }
                     this.minValue = value;
              }
       }

       public int MaxValue
       {
              get
              {
                     return this.maxValue;
              }
              set
              {
                     if (value <= this.MinValue)
                     {
                            throw new ArgumentOutOfRangeException("MaxValue",
"MaxValue cannot be equal or lower than MinValue");
                     }
                     this.maxValue = value;
              }
       }

       public int Increment
       {
              get
              {
                     return this.increment;
              }
              set
              {
                     if (value < 1)
                     {
                            throw new ArgumentOutOfRangeException("Increment",
"Increment cannot be less than or equal to zero");
                     }
                     this.increment = value;
              }
       }

       public override object GetNext(object relativeTo)
       {
              int nextValue = (int)relativeTo + this.Increment;
              if (nextValue > this.MaxValue)
              {
                     nextValue = this.MinValue;
              }



www.windowsphonegeek.com
                                                                                 134
Silverlight for Windows Phone Toolkit in Depth



                 return nextValue;
          }

          public override object GetPrevious(object relativeTo)
          {
                 int prevValue = (int)relativeTo - this.Increment;
                 if (prevValue < this.MinValue)
                 {
                        prevValue = this.MaxValue;
                 }
                 return prevValue;
          }
}




Note that we have added some validation for the Min/Max values and some Next/Previous
logic in the GetNext/GetPrevious methods.
         Populating Loopingselector with IntLoopingDataSource
The final step is to populate the LoopingSelector with our IntLoopingDataSource. The code is:
C#

this.selector.DataSource = new IntLoopingDataSource() { MinValue = 1, MaxValue
= 60, SelectedItem = 1 };




         NOTE: We also used the MinValue = 1, MaxValue = 60, SelectedItem = 1 properties of our
         data source.

The result of this example can be seen in the next screenshots:




www.windowsphonegeek.com
                                                                                                  135
Silverlight for Windows Phone Toolkit in Depth




      NOTE: DatePicker and TimePicker from the Silverlight for Windows Phone 7 toolkit are
      based on LoopingSelector.


Key Properties
DataSource
DataSource is a dependency property of type ILoopingSelectorDataSource. It represents the
data source of the control.

IsExpanded
IsExpanded is a dependency property of type bool and controls the expanded state of the
control.

ItemTemplate
ItemTemplate is a dependency property of type DataTemplate. It specifies the control
ItemTemplate.

ItemSize
ItemSize is a property of type Size. It specifies the size of the items, excluding the ItemMargin.

ItemMargin
ItemMargin is a property of type Thickness. It specifies the margin around the items, to be a
part of the touchable area.

Key Events
IsExpandedChanged
The IsExpandedChanged event will be raised whenever the value of the IsExpanded property
changes.
Example:
C#
this.selector.IsExpandedChanged += new
DependencyPropertyChangedEventHandler(selector_IsExpandedChanged);
//...
void selector_IsExpandedChanged(object sender, DependencyPropertyChangedEventArgs e)
{
  //...
}



www.windowsphonegeek.com
                                                                                                     136
Silverlight for Windows Phone Toolkit in Depth




ILoopingSelectorDataSource
This is the interface that defines how the LoopingSelector communicates with its data source.
Fields:

GetNext(object relativeTo)
Get the next datum, relative to an existing datum where "relativeTo" is the datum the return
value will be relative to.

GetPrevious(object relativeTo);
Get the previous datum, relative to an existing datum where "relativeTo" is the datum the
return value will be relative to.

SelectedItem
The selected item. Should never be null.

SelectionChanged
Raised when the selection changes.
Example:
C#

event EventHandler<SelectionChangedEventArgs> SelectionChanged;




Implementing a generic LoopingSelectorDataSource
This example demonstrates how to implement a generic ListLoopingDataSource class which
derives from LoopingDataSourceBase and implements a generic looping data source that can be
used to show any list of items with the LoopingSelector control.

In order to effectively find the previous and next items for a given item the following things are
used:

        a linked list that contains the items that are going to be shown:

C#

private LinkedList<T> linkedList;




www.windowsphonegeek.com
                                                                                                     137
Silverlight for Windows Phone Toolkit in Depth




        a sorted list of linked list nodes that is used to quickly find the node corresponding to a
         given item:

C#

private List<LinkedListNode<T>> sortedList;


        a node comparer that is used for sorting and searching in the node list:
C#

private class NodeComparer : IComparer<LinkedListNode<T>>
{
       private IComparer<T> comparer;

         public NodeComparer(IComparer<T> comparer)
         {
                this.comparer = comparer;
         }

         #region IComparer<LinkedListNode<T>> Members

         public int Compare(LinkedListNode<T> x, LinkedListNode<T> y)
         {
                return this.comparer.Compare(x.Value, y.Value);
         }

         #endregion
}


        Items property that represents the collection of items with which the LoopingSelector is
         initialized.

C#

public IEnumerable<T> Items
{
       get
       {
              return this.linkedList;
       }
       set
       {
              this.SetItemCollection(value);
       }
}




www.windowsphonegeek.com
                                                                                                       138
Silverlight for Windows Phone Toolkit in Depth




        Next/Previous logic we find the index of the node using binary search in the sorted list.
         After that, get the actual node from the linked list using the index. And finally if there is
         no next node we get the first one and if there is no previous node we get the last one.

The final code of our ListLoopingDataSource<T> class looks like:

C#

public class ListLoopingDataSource<T> : LoopingDataSourceBase
{
       private LinkedList<T> linkedList;
       private List<LinkedListNode<T>> sortedList;
       private IComparer<T> comparer;
       private NodeComparer nodeComparer;

         public ListLoopingDataSource()
         {
         }

         public IEnumerable<T> Items
         {
                get
                {
                       return this.linkedList;
                }
                set
                {
                       this.SetItemCollection(value);
                }
         }

         private void SetItemCollection(IEnumerable<T> collection)
         {
                this.linkedList = new LinkedList<T>(collection);

              this.sortedList = new
List<LinkedListNode<T>>(this.linkedList.Count);
              // initialize the linked list with items from the collections
              LinkedListNode<T> currentNode = this.linkedList.First;
              while (currentNode != null)
              {
                     this.sortedList.Add(currentNode);
                     currentNode = currentNode.Next;
              }

                IComparer<T> comparer = this.comparer;
                if (comparer == null)
                {
                       // if no comparer is set use the default one if available
                       if (typeof(IComparable<T>).IsAssignableFrom(typeof(T)))
                       {
                              comparer = Comparer<T>.Default;
                       }
                       else



www.windowsphonegeek.com
                                                                                                         139
Silverlight for Windows Phone Toolkit in Depth



                       {
                            throw new InvalidOperationException("There is no
default comparer for this type of item. You must set one.");
                     }
              }

               this.nodeComparer = new NodeComparer(comparer);
               this.sortedList.Sort(this.nodeComparer);
       }

       public IComparer<T> Comparer
       {
              get
              {
                     return this.comparer;
              }
              set
              {
                     this.comparer = value;
              }
       }

       public override object GetNext(object relativeTo)
       {
              // find the index of the node using binary search in the sorted
list
              int index = this.sortedList.BinarySearch(new
LinkedListNode<T>((T)relativeTo), this.nodeComparer);
              if (index < 0)
              {
                     return default(T);
              }

               // get the actual node from the linked list using the index
               LinkedListNode<T> node = this.sortedList[index].Next;
               if (node == null)
               {
                      // if there is no next node get the first one
                      node = this.linkedList.First;
               }
               return node.Value;
       }

       public override object GetPrevious(object relativeTo)
       {
              int index = this.sortedList.BinarySearch(new
LinkedListNode<T>((T)relativeTo), this.nodeComparer);
              if (index < 0)
              {
                     return default(T);
              }
              LinkedListNode<T> node = this.sortedList[index].Previous;
              if (node == null)
              {
                     // if there is no previous node get the last one
                     node = this.linkedList.Last;



www.windowsphonegeek.com
                                                                                140
Silverlight for Windows Phone Toolkit in Depth



               }
               return node.Value;
       }

       private class NodeComparer : IComparer<LinkedListNode<T>>
       {
              private IComparer<T> comparer;

               public NodeComparer(IComparer<T> comparer)
               {
                      this.comparer = comparer;
               }

               #region IComparer<LinkedListNode<T>> Members

               public int Compare(LinkedListNode<T> x, LinkedListNode<T> y)
               {
                      return this.comparer.Compare(x.Value, y.Value);
               }

               #endregion
       }

}


After implementing the ListLoopingDataSource<T> generic data source class the next step is to
define some LoopingSelector controls and finally populating them with data.


LoopingSelector with Double Data
This example demonstrates how to implement a LoopingSelector that displays double data
using the previously created ListLoopingDataSource<T> generic data source class(check the
previous section for reference).

XAML

<toolkit:LoopingSelector Grid.Column="0" x:Name="selectorDouble"
ItemMargin="2,3,3,2" ItemSize="100,100" FontSize="33"/>


In order to populate the selector with data the following code is used:

C#

List<double> doubleNumbers = new List<double> { 1.1, 2.15, 3.66, 4.457, 5.036,
6.7, 7.4, 8.54, 9.11 };
this.selectorDouble.DataSource = new ListLoopingDataSource<double>() { Items =
doubleNumbers, SelectedItem = 6.7 };




www.windowsphonegeek.com
                                                                                                141
Silverlight for Windows Phone Toolkit in Depth




       NOTE: The selected item should never be null!



       NOTE: Most of the basic types from the .NET framework implement IComparable<T> so
       setting a comparer when using such a type is not necessary however, if you are using this
       class with some custom item type you must either implement IComparable<TItem> on
your item class or explicitly set a suitable comparer.

Here is how the final result looks like:




LoopingSelector with Int Data
This example demonstrates how to implement a LoopingSelector that displays int data. A
custom ItemTemplate is added in order to customize the appearance of the items.

XAML

<toolkit:LoopingSelector Grid.Column="1" x:Name="selectorInt" ItemMargin="2,3,3,2"
ItemSize="100,100" FontSize="38">
       <toolkit:LoopingSelector.ItemTemplate>
              <DataTemplate>
                     <Grid>
                       <TextBlock Text="{Binding}" FontSize="50"
HorizontalAlignment="Center" VerticalAlignment="Center" />
                     </Grid>
              </DataTemplate>
       </toolkit:LoopingSelector.ItemTemplate>
</toolkit:LoopingSelector>



www.windowsphonegeek.com
                                                                                                   142
Silverlight for Windows Phone Toolkit in Depth




In order to populate the selector with data the following code is used:

C#

List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
this.selectorInt.DataSource = new ListLoopingDataSource<int>() { Items =
numbers ,SelectedItem = 5};


Here is how the final result looks like:




LoopingSelector with String Data
This example demonstrates how to implement a LoopingSelector that displays string data.

XAML

<toolkit:LoopingSelector Grid.Column="2" x:Name="selectorString"
ItemMargin="2,3,3,2" ItemSize="100,100" FontSize="18"/>



In order to populate the selector with data the following code is used:

C#

string[] cityNames = new string[] { "London", "New York", "Barcelona",
"Madrid", "Berlin", "Bonn", "Munich", "Las Vegas" };
this.selectorString.DataSource = new ListLoopingDataSource<string>() { Items =
cityNames, SelectedItem = "Madrid" };




www.windowsphonegeek.com
                                                                                          143
Silverlight for Windows Phone Toolkit in Depth



Here is how the final result looks like:




LoopingSelector with DateTime Data
This example demonstrates how to implement a LoopingSelector that displays DateTime data.
A custom ItemTemplate is added in order to customize the appearance of the items.

XAML

<toolkit:LoopingSelector Grid.Column="3" x:Name="selectorDateTime"
ItemMargin="5" Width="160" ItemSize="160,105" >
       <toolkit:LoopingSelector.ItemTemplate>
              <DataTemplate>
                     <Grid>
                            <TextBlock Text="{Binding}" FontSize="15"
HorizontalAlignment="Center" VerticalAlignment="Center" />
                     </Grid>
              </DataTemplate>
       </toolkit:LoopingSelector.ItemTemplate>
</toolkit:LoopingSelector>


In order to populate the selector with data the following code is used:
C#

List<DateTime> dates = new List<DateTime>();
DateTime selectedDate = DateTime.Now;
dates.Add(selectedDate);
dates.Add(DateTime.Now.AddMonths(1));
dates.Add(DateTime.Now.AddMonths(2));



www.windowsphonegeek.com
                                                                                            144
Silverlight for Windows Phone Toolkit in Depth



dates.Add(DateTime.Now.AddMonths(3));
dates.Add(DateTime.Now.AddMonths(4));
dates.Add(DateTime.Now.AddMonths(5));
dates.Add(DateTime.Now.AddMonths(6));
this.selectorDateTime.DataSource = new ListLoopingDataSource<DateTime>() {
Items = dates, SelectedItem = selectedDate};


Here is how the final result looks like:




Advanced Data Binding using IComparable<T>
This example demonstrates:

      How to populate the LongListSelector control with a custom business object which
       implements IComparable<T>
      How to customize the look of the items through different ItemTemplates


      NOTE: Most of the basic types from the .NET framework implement IComparable<T> so
      setting a comparer when using such a type is not necessary however, if you are using this
class with a some custom item type you must either implement IComparable<TItem> on your
item class or explicitly set a suitable comparer.

Basically in this example we will create two different data types: CountryData and CityData. The
first one will implement IComparable<CountryData> and the second one will use a separate
CityDataComparer class. We will use a set of images in order to visualize the country flags.


www.windowsphonegeek.com
                                                                                                   145
Silverlight for Windows Phone Toolkit in Depth




      NOTE: There are two ways to include an image in a Windows Phone 7 project. As Content
      or a Resource. Resources are included in your assembly (DLL) while content is included in
      your deployment package (XAP) alongside the DLL.

I would suggest that you always compile your images with a "Build Action" of "Content" instead
of the default "Resource" in order to reduce the size of your DLL, speeding up both app load
and image load.

Step1. Creating a Business object which implements IComparable<T>

This step demonstrates how to create a sample class that gives information about countries:
Name, Flag and ID. Because this class is a custom type, not one of the basic types from the .NET
framework which implement IComparable<T>, we will have to handle this on our own. The
class looks like:

C#

// option 1: implement IComparable<T>
public class CountryData : IComparable<CountryData>
{
       public string Name
       {
              get;
              set;
       }

       public string Flag
       {
              get;
              set;
       }
       public int ID
       {
              get;
              set;
       }

       #region IComparable<CityData> Members

       public int CompareTo(CountryData other)
       {
              return this.ID.CompareTo(other.ID);
       }

       #endregion
}




www.windowsphonegeek.com
                                                                                                   146
Silverlight for Windows Phone Toolkit in Depth




Step2. Create an instance of a LoopingSelector in XAML and add a custom ItemTemplate in
order to visualize the data in attractive way. The code is as follows:

XAML

<toolkit:LoopingSelector Grid.Column="0" x:Name="selectorLeft" ItemMargin="5"
ItemSize="160,160" >
       <toolkit:LoopingSelector.ItemTemplate>
              <DataTemplate>
                     <StackPanel>
                            <TextBlock Text="{Binding Name}"/>
                            <Image Source="{Binding Flag}" Stretch="None"/>
                            <TextBlock Text="{Binding ID}"/>
                     </StackPanel>
              </DataTemplate>
       </toolkit:LoopingSelector.ItemTemplate>
</toolkit:LoopingSelector>



Step3. Populate the LoopingSelector through its DataSource property. The code for
accomplishing this is as follows:

C#

List<CountryData> data = new List<CountryData>();
data.Add(new CountryData() { Name = "Germany", Flag = new Uri(@"../Images/Germany.png",
UriKind.Relative).ToString(), ID = 1 });
data.Add(new CountryData() { Name = "Greece", Flag = new Uri(@"../Images/Greece.png",
UriKind.Relative).ToString(), ID = 2 });
data.Add(new CountryData() { Name = "France", Flag = new Uri(@"../Images/France.png",
UriKind.Relative).ToString(), ID = 3 });
data.Add(new CountryData() { Name = "Italy", Flag = new Uri(@"../Images/Italy.png",
UriKind.Relative).ToString(), ID = 4 });
data.Add(new CountryData() { Name = "Spain", Flag = new Uri(@"../Images/Spain.png",
UriKind.Relative).ToString(), ID = 5 });
data.Add(new CountryData() { Name = "UK", Flag = new Uri(@"../Images/UK.png",
UriKind.Relative).ToString(), ID = 6 });
this.selectorLeft.DataSource = new ListLoopingDataSource<CountryData>() { Items = data,
SelectedItem = data[2] };




       NOTE: The "Build Action" of the images is "Content" instead of the default "Resource" in
       order to reduce the size of your DLL, speeding up both app load and image load. So you
       can access them using UriKind.Relative.




www.windowsphonegeek.com
                                                                                                  147
Silverlight for Windows Phone Toolkit in Depth




Step4. Setting the DataSource

C#

this.selectorLeft.DataSource = new ListLoopingDataSource<CountryData>() { Items = data,
SelectedItem = data[2] };




     NOTE: Because our custom class CountryData implements
     IComparable<CountryData> there is no need to set any additional comparer when
     initializing the items collection. All we have to do is just to set Items and SelectedItem
properties of our ListLoopingDataSource.

The final result can be seen on the following screen shots:




Advanced Data Binding using a separate Comparer
This example demonstrates:

        How to populate the LongListSelector control with custom business objects which use a
         separate Comparer.
        How to customize the look of the items through different ItemTemplates




www.windowsphonegeek.com
                                                                                                  148
Silverlight for Windows Phone Toolkit in Depth




Step1. Create a sample class that gives information about cities: Name, Country and ID. This
time we will not implement IComparable<T> but will use a separate CityDataComparer. The
source code looks like:

C#
// option 2: implement and use IComparer<T>
public class CityDataComparer : IComparer<CityData>
{
       #region IComparer<CityData> Members

       public int Compare(CityData x, CityData y)
       {
              return x.ID.CompareTo(y.ID);
       }

       #endregion
}

public class CityData
{
       public string Name
       {
              get;
              set;
       }

       public string Country
       {
              get;
              set;
       }

       public int ID
       {
              get;
              set;
       }
}

Step2. Create an instance of a LoopingSelector in XAML and add a custom ItemTemplate in
order to visualize the data in an attractive way. The purpose is to implement a similar look to
this in the CountryData example above but this time we will use a separate CityDataComparer.
The code is as follows:

XAML
<toolkit:LoopingSelector Grid.Column="1" x:Name="selectorRight" ItemMargin="5"
ItemSize="160,160" >
       <toolkit:LoopingSelector.ItemTemplate>
              <DataTemplate>
                     <StackPanel>
                            <TextBlock Text="{Binding Name}"/>
                            <Image Source="{Binding Country}" Stretch="None"/>



www.windowsphonegeek.com
                                                                                                  149
Silverlight for Windows Phone Toolkit in Depth



                            <TextBlock Text="{Binding ID}"/>
                     </StackPanel>
              </DataTemplate>
       </toolkit:LoopingSelector.ItemTemplate>
</toolkit:LoopingSelector>


Step3. Populate the LoopingSelector through its DataSource property. The code for
accomplishing this is as follows:

C#

List<CityData> cityData = new     List<CityData>();
cityData.Add(new CityData() {     Name = "Berlin", Country = new Uri(@"../Images/Germany.png",
UriKind.Relative).ToString(),     ID = 1 });
cityData.Add(new CityData() {     Name = "Solon", Country = new Uri(@"../Images/Greece.png",
UriKind.Relative).ToString(),     ID = 2 });
cityData.Add(new CityData() {     Name = "Paris", Country = new Uri(@"../Images/France.png",
UriKind.Relative).ToString(),     ID = 3 });
cityData.Add(new CityData() {     Name = "Rome", Country = new Uri(@"../Images/Italy.png",
UriKind.Relative).ToString(),     ID = 4 });
cityData.Add(new CityData() {     Name = "Madrid", Country = new Uri(@"../Images/Spain.png",
UriKind.Relative).ToString(),     ID = 5 });
cityData.Add(new CityData() {     Name = "London", Country = new Uri(@"../Images/UK.png",
UriKind.Relative).ToString(),     ID = 6 });

this.selectorRight.DataSource = new ListLoopingDataSource<CityData>() { Comparer = new
CityDataComparer(), Items = cityData, SelectedItem = cityData[2] };




      NOTE: Because CityData class does not implement IComparable<T> we will need to set
      an additional comparer before we initialize the items collection. All we have to do is just
      to first initialize the Comparer and after that set Items and SelectedItem properties of our
ListLoopingDataSource !

Step4. The final result can be seen on the
following screen shots:




www.windowsphonegeek.com
                                                                                                     150
Silverlight for Windows Phone Toolkit in Depth




LongListSelector
Overview
Basically, LongListSelector is an advanced ListBox that supports full data and UI virtualization,
flat lists and grouped lists. It helps users to scroll through long lists of data. Basically a quick
jump grid overlays the list when the user selects one of the group headers. After that, when an
item is selected from the grid, the user is automatically redirected back to the long list at the
selected point.
Generally when talking about the LongListSelector and populating it with data you have two
choices:
    use it as a standard ListBox with flat lists.
    use it as an advanced ListBox with grouped lists.


      NOTE: LongListSelector supports full data and UI virtualization. It is usually used to scroll
      through long lists of data.


Visual structure
Flat List scenario
When using LongListSelector in flat mode it behaves as a ListBox with header and footer
(without any groups). In the following diagram you can see the basic visual elements:




www.windowsphonegeek.com
                                                                                                       151
Silverlight for Windows Phone Toolkit in Depth




Grouped List scenario
In the following diagrams you can see the basic visual elements:




www.windowsphonegeek.com
                                                                   152
Silverlight for Windows Phone Toolkit in Depth




Getting Started
To begin using LongListSelector first add a reference to the
Microsoft.Phone.Controls.Toolkit.dll assembly in your Windows Phone application project.

        NOTE: Microsoft.Phone.Controls.Toolkit.dll assembly is installed with the toolkit and you
        can find it in:
        For 32-bit systems:
        C:\Program Files\Microsoft SDKs\Windows
        Phone\v7.1\Toolkit\Aug11\Bin\Microsoft.Phone.Controls.Toolkit.dll
        For 64-bit systems:
        C:\Program Files (x86)\Microsoft SDKs\Windows
        Phone\v7.1\Toolkit\Aug11\Bin\Microsoft.Phone.Controls.Toolkit.dll

        Alternatively you can select it directly from the “...\Silverlight for Windows Phone Toolkit
        Source & Sample - Aug 2011\Bin\” if you have downloaded the “Silverlight for Windows
        Phone Toolkit Source & Sample - Aug 2011.zip” instead.

You can create a LongListSelector instance either in XAML or with C#/VB.

       Define a LongListSelector instance in XAML: you have to add the following namespace
        declaration (for example):

xmlns:toolkit="clr-
namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"

XAML

<toolkit:LongListSelector/>
<toolkit:LongListSelector
ItemsSource="{StaticResource movies}"
ListHeaderTemplate="{StaticResource movieListHeader}"
GroupHeaderTemplate="{StaticResource movieGroupHeader}"
GroupFooterTemplate="{StaticResource movieGroupFooter}"
GroupItemTemplate="{StaticResource groupItemHeader}"
ItemTemplate="{StaticResource movieItemTemplate}">
</toolkit:LongListSelector>




       NOTE: Make sure that your page declaration includes the "toolkit" namespace! You can
       do this by using Visual Studio Toolbox, Expression Blend Designer or just include it on your
       own.




www.windowsphonegeek.com
                                                                                                       153
Silverlight for Windows Phone Toolkit in Depth




         Define a LongListSelector instance in C#: just add the following using directive:

using Microsoft.Phone.Controls;

C#
LongListSelector longListSelector = new LongListSelector();




         NOTE: If choosing to add this control via C# code then do not forget to associate it to a
         panel on your page for example: this.ContentPanel.Children.Add(longListSelector);



Key Properties
DisplayAllGroups
DisplayAllGroups is a dependency property of type bool. When set to true, all groups are
displayed whether or not they have items. The default is false.


GroupFooterTemplate
GroupFooterTemplate is a dependency property of type DataTemplate. It provides the
template for the groups in the items view.
Example:
XAML

<phone:PhoneApplicationPage.Resources>
       <DataTemplate x:Key="movieGroupFooter">
              <Border Background="{StaticResource PhoneAccentBrush}"
Padding="{StaticResource PhoneTouchTargetOverhang}">
                     <!--add some content here-->
              </Border>
       </DataTemplate>
</phone:PhoneApplicationPage.Resources>




XAML

<toolkit:LongListSelector ListFooterTemplate="{StaticResource
movieListFooter}" GroupFooterTemplate="{StaticResource movieGroupFooter}"
GroupItemTemplate="{StaticResource groupItemHeader}"
ItemTemplate="{StaticResource movieItemTemplate}"/>




www.windowsphonegeek.com
                                                                                                     154
Silverlight for Windows Phone Toolkit in Depth




GroupHeaderTemplate
GroupHeaderTemplate is a dependency property of type DataTemplate. It provides the
template for the groups in the items view.
Example:
XAML

<phone:PhoneApplicationPage.Resources>
       <DataTemplate x:Key="movieGroupHeader">
              <Border Background="{StaticResource PhoneAccentBrush}"
Padding="{StaticResource PhoneTouchTargetOverhang}">
                     <TextBlock Text="{Binding Key}" Style="{StaticResource
PhoneTextLargeStyle}"/>
              </Border>
       </DataTemplate>
</phone:PhoneApplicationPage.Resources>



XAML

<toolkit:LongListSelector ListFooterTemplate="{StaticResource
movieListFooter}" GroupHeaderTemplate="{StaticResource movieGroupHeader}"
GroupItemTemplate="{StaticResource groupItemHeader}"
ItemTemplate="{StaticResource movieItemTemplate}"/>




GroupItemsPanel
GroupItemsPanel is a dependency property of type ItemsPanelTemplate. It specifies the panel
that will be used in group view mode.
Example:
XAML

<toolkit:LongListSelector>
       <toolkit:LongListSelector.GroupItemsPanel>
              <ItemsPanelTemplate>
                     <toolkit:WrapPanel Orientation="Horizontal"/>
              </ItemsPanelTemplate>
       </toolkit:LongListSelector.GroupItemsPanel>
</toolkit:LongListSelector>




GroupItemTemplate
GroupItemTemplate is a dependency property of type DataTemplate. It specifies the template
that will be used in group view mode.


www.windowsphonegeek.com
                                                                                              155
Silverlight for Windows Phone Toolkit in Depth




Example:
XAML

<phone:PhoneApplicationPage.Resources>
       <DataTemplate x:Key="groupItemHeader">
              <Border Background="{StaticResource PhoneAccentBrush}"
Margin="{StaticResource PhoneTouchTargetOverhang}" Padding="{StaticResource
PhoneTouchTargetOverhang}">
                     <TextBlock Text="{Binding Key}" Style="{StaticResource
PhoneTextLargeStyle}"/>
              </Border>
       </DataTemplate>
</phone:PhoneApplicationPage.Resources>




XAML

<toolkit:LongListSelector ListFooterTemplate="{StaticResource
movieListFooter}" GroupFooterTemplate="{StaticResource movieGroupFooter}"
GroupItemTemplate="{StaticResource groupItemHeader}"
ItemTemplate="{StaticResource movieItemTemplate}"/>




IsFlatList
IsFlatList is a property of type bool. It is set to true when the list is flat instead of a group
hierarchy.

IsScrolling
IsScrolling is a read only property of type bool. It returns true if the user is manipulating the list,
or if an inertial animation is taking place. This property has a private setter so you can only get
its value.

ItemSource
ItemSource gets or sets a collection used to generate the content of the LongListSelector.

ItemTemplate
ItemTemplate is a dependency property of type DataTemplate. It provides the template for the
items in the items view.




www.windowsphonegeek.com
                                                                                                          156
Silverlight for Windows Phone Toolkit in Depth




Example:
XAML

<phone:PhoneApplicationPage.Resources>
       <DataTemplate x:Key="movieItemTemplate">
              <Grid Margin="{StaticResource PhoneTouchTargetOverhang}">
                     <!--add some content here-->
              </Grid>
       </DataTemplate>
</phone:PhoneApplicationPage.Resources>




XAML

<toolkit:LongListSelector ListFooterTemplate="{StaticResource
movieListFooter}" GroupFooterTemplate="{StaticResource movieGroupFooter}"
GroupItemTemplate="{StaticResource groupItemHeader}"
ItemTemplate="{StaticResource movieItemTemplate}"/>




ListFooter
ListFooter is a dependency property of type object. It will be used as the last scroll Item in the
list.

ListFooterTemplate
ListFooterTemplate is a dependency property of type DataTemplate. It provides the template
for the ListFooter.
 Example:
XAML

<phone:PhoneApplicationPage.Resources>
       <DataTemplate x:Key="movieListFooter">
              <TextBlock Text="List footer" Style="{StaticResource
PhoneTextTitle1Style}"/>
       </DataTemplate>
</phone:PhoneApplicationPage.Resources>



XAML

<toolkit:LongListSelector ListFooterTemplate="{StaticResource
movieListFooter}" GroupHeaderTemplate="{StaticResource movieGroupHeader}"
GroupItemTemplate="{StaticResource groupItemHeader}"
ItemTemplate="{StaticResource movieItemTemplate}"/>




www.windowsphonegeek.com
                                                                                                     157
Silverlight for Windows Phone Toolkit in Depth




ListHeader
ListHeader is a dependency property of type object. It will be used as the first scroll Item in the
list.


ListHeaderTemplate
ListHeaderTemplate is a dependency property of type DataTemplate. It provides the template
for the ListHeader.
Example:
XAML

<phone:PhoneApplicationPage.Resources>
       <DataTemplate x:Key="movieListHeader">
              <TextBlock Text="list header" Style="{StaticResource
PhoneTextTitle1Style}"/>
       </DataTemplate>
</phone:PhoneApplicationPage.Resources>



XAML

<toolkit:LongListSelector ListHeaderTemplate="{StaticResource
movieListHeader}" GroupHeaderTemplate="{StaticResource movieGroupHeader}"
GroupItemTemplate="{StaticResource groupItemHeader}"
ItemTemplate="{StaticResource movieItemTemplate}"/>



SelectedItem
Gets or sets the selected item.


ShowListFooter
ShowListFooter is a dependency property of type bool. It controls whether or not the ListFooter
is shown. The default is true.

ShowListHeader
ShowListHeader is a dependency property of type bool. It controls whether or not the
ListHeader is shown. The default is true.


MaximumFlickVelocity
The MaximumFlickVelocity property is obsolete and is not used anymore.




www.windowsphonegeek.com
                                                                                                      158
Silverlight for Windows Phone Toolkit in Depth




IsBouncy
The IsBouncy property is obsolete. IsBouncy is always set to true.


BufferSize
The BufferSize property is obsolete and it no longer affects items virtualization.


Key Events
Link
Indicates that the ContentPresenter with the item is about to be "realized".
Example:
C#

selector.Link += new EventHandler<LinkUnlinkEventArgs>(selector_Link);

//...

void selector_Link(object sender, LinkUnlinkEventArgs e)
{
       //...
}




Unlink
Indicates that the ContentPresenter with the item is being recycled and is becoming "un-
realized".
Example:
C#

selector.Unlink += new EventHandler<LinkUnlinkEventArgs>(selector_Unlink);
//...
void selector_Unlink(object sender, LinkUnlinkEventArgs e)
{
       //...
}




www.windowsphonegeek.com
                                                                                           159
Silverlight for Windows Phone Toolkit in Depth




SelectionChanged
The SelectionChanged event.
Example:
C#

selector.SelectionChanged += new
SelectionChangedEventHandler(selector_SelectionChanged);

//...

void selector_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
       //...
}




ScrollingCompleted
Fired when the user has finished a drag or a flick completes.
Example:
C#

selector.ScrollingCompleted += new EventHandler(selector_ScrollingCompleted);
//...
void selector_ScrollingCompleted(object sender, EventArgs e)
{
       //...
}




ScrollingStarted
Fired when the user is manipulating the list.

Example:
C#

selector.ScrollingStarted += new EventHandler(selector_ScrollingStarted);
//...
void selector_ScrollingStarted(object sender, EventArgs e)
{
       //...
}




www.windowsphonegeek.com
                                                                                160
Silverlight for Windows Phone Toolkit in Depth




GroupViewOpened
Fired when the group Popup's IsOpen has been set to true.
Example:
C#

selector.GroupViewOpened += new
EventHandler<GroupViewOpenedEventArgs>(selector_GroupViewOpened);
//...
void selector_GroupViewOpened(object sender, GroupViewOpenedEventArgs e)
{
       //...
}




GroupViewClosing
Fired when the group popup is about to close.
Example:
C#

selector.GroupViewClosing += new
EventHandler<GroupViewClosingEventArgs>(selector_GroupViewClosing);
//...
void selector_GroupViewClosing(object sender, GroupViewClosingEventArgs e)
{
       //...
}




StretchingBottom
Fired when IsBouncy is true and the user has dragged the items up from the bottom as far as
they can go.
Example:
C#

selector.StretchingBottom += new EventHandler(selector_StretchingBottom);
//...
void selector_StretchingBottom(object sender, EventArgs e)
{
       //...
}




www.windowsphonegeek.com
                                                                                              161
Silverlight for Windows Phone Toolkit in Depth




StretchingCompleted
Fired when the user is no longer stretching.

Example:
C#

selector.StretchingCompleted += new
EventHandler(selector_StretchingCompleted);
//...
void selector_StretchingCompleted(object sender, EventArgs e)
{
       //...
}




StretchingTop
Fired when IsBouncy is true and the user has dragged the items down from the top as far as
they can go.
Example:
C#

selector.StretchingTop += new EventHandler(selector_StretchingTop);
//...
void selector_StretchingTop(object sender, EventArgs e)
{
       //...
}




Key Methods
DisplayGroupView()
Will invoke the group view, if a GroupItemTemplate has been defined.


CloseGroupView()
Closes the group view unconditionally.


      NOTE: CloseGroupView does not raise the GroupViewClosingEventArgs event!




www.windowsphonegeek.com
                                                                                             162
Silverlight for Windows Phone Toolkit in Depth




ScrollTo(object item)
Instantly jump to the specified item (The item to scroll to).

ScrollToGroup(object group)
Instantly jump to the specified group.


AnimateTo(object item)
AnimateTo(...) is obsolete, call ScrollTo(...) to jump without animation to the given item.

GetItemsWithContainers(…)
GetItemsWithContainers(...) is obsolete, it always returns an empty collection of items. Rely on
Link/Unlink to know an item get realized or unrealized.


GetItemsInView()
GetItemsInView() is obsolete, it always returns an empty collection of items. Rely on
Link/Unlink to know an item get realized or unrealized.


Data Binding LongListSelector
This example demonstrates how to populate LongListSelector with data using data binding in
both scenarios

     1.   Flat lists.
     2.   Grouped lists.

Defining the Data Source
Here are the steps we will follow in order to create a data source:

         Define the business/data class:

C#

public class City
{
       public string Name
       {
              get;
              set;
       }




www.windowsphonegeek.com
                                                                                                   163
Silverlight for Windows Phone Toolkit in Depth



         public string Country
         {
                get;
                set;
         }

         public string Language
         {
                get;
                set;
         }
}



        Create a sample collection with items of type City:

C#

List<City> source = new     List<City>();
source.Add(new City() {     Name = "Madrid", Country = "ES", Language = "Spanish" });
source.Add(new City() {     Name = "Barcelona", Country = "ES", Language = "Spanish" });
source.Add(new City() {     Name = "Mallorca", Country = "ES", Language = "Spanish" });
source.Add(new City() {     Name = "Las Vegas", Country = "US", Language = "English" });
source.Add(new City() {     Name = "Dalas", Country = "US", Language = "English" });
source.Add(new City() {     Name = "New York", Country = "US", Language = "English" });
source.Add(new City() {     Name = "London", Country = "UK", Language = "English" });
source.Add(new City() {     Name = "Mexico", Country = "MX", Language = "Spanish" });
source.Add(new City() {     Name = "Milan", Country = "IT", Language = "Italian" });
source.Add(new City() {     Name = "Roma", Country = "IT", Language = "Italian" });
source.Add(new City() {     Name = "Paris", Country = "FR", Language = "French" });



1. FlatList implementation
The first thing to do when using flat lists is to set IsFlatList="True".

      Simple Flat List
Let’s say we want to show a standard list structure with minimum efforts in our
LongListSelector. The source code for accomplishing this is as follows:

XAML
<toolkit:LongListSelector x:Name="citiesList" Background="Transparent"
IsFlatList="True"/>



C#
this.citiesList.ItemsSource = new List<string> { "Madrid", "Barcelona", "Mallorca",
"Las Vegas" };




www.windowsphonegeek.com
                                                                                           164
Silverlight for Windows Phone Toolkit in Depth




The result is:




     Complex Flat List
In more composite flat scenarios you can use more complex data, define your own
ItemTemplates and customize the appearance of the items. For instance in this example we will
show the names of the countries, cities and the specified languages in different colors. Let’s add
some elements to the ItemTemplate, ListHeaderTemplate and ListFooterTemplate. The source
code is:

Step1. Add the following DataTemplates to the page Resources section:

XAML

<phone:PhoneApplicationPage.Resources>
       <DataTemplate x:Key="citiesListHeader">
              <Border Background="Purple">
                     <TextBlock Text="Cities Header" />
              </Border>
       </DataTemplate>
       <DataTemplate x:Key="citiesListFooter">
              <Border Background="Green">
                     <TextBlock Text="Cities Footer" />
              </Border>
       </DataTemplate>

       <DataTemplate x:Key="citiesItemTemplate">
              <StackPanel Grid.Column="1" VerticalAlignment="Top">
                     <TextBlock Text="{Binding Name}" FontSize="26" Margin="12,-
12,12,6"/>
                     <TextBlock Text="{Binding Country}" Foreground="GreenYellow"/>
                     <TextBlock Text="{Binding Language}" Foreground="Orange" />
              </StackPanel>
       </DataTemplate>
</phone:PhoneApplicationPage.Resources>




www.windowsphonegeek.com
                                                                                                     165
Silverlight for Windows Phone Toolkit in Depth




Step2. Define an instance of LongListSelector and add the previously declared DataTemplates in
this way:

XAML

<toolkit:LongListSelector x:Name="citiesList" Background="Transparent"
IsFlatList="True" ItemTemplate="{StaticResource citiesItemTemplate}"
ListHeaderTemplate="{StaticResource citiesListHeader}"
ListFooterTemplate="{StaticResource citiesListFooter}" />



Step3. Set the newly created data source (from the previous section) as ItemsSource of the
LongListSelector.

C#
this.citiesList.ItemsSource = source;



Step4. The final result should look like the following:




Generally when used in Flat mode the LongListSelector is nothing more than a List with Header
and Footer.

2. Grouped Lists implementation
This is the more complex scenario. In order to have a hierarchy with groups, IsFlatList must be
set to False which is actually its default value.

Step1. Implementing the group hierarchy

In order to fit in the ItemsSource requirements the group class should implement IEnumerable.
In our case it looks like the following:




www.windowsphonegeek.com
                                                                                                  166
Silverlight for Windows Phone Toolkit in Depth




C#

public class Group<T> : IEnumerable<T>
{
       public Group(string name, IEnumerable<T> items)
       {
              this.Title = name;
              this.Items = new List<T>(items);
       }

       public override bool Equals(object obj)
       {
              Group<T> that = obj as Group<T>;

               return (that != null) && (this.Title.Equals(that.Title));
       }

       public string Title
       {
              get;
              set;
       }

       public IList<T> Items
       {
              get;
              set;
       }

       #region IEnumerable<T> Members

       public IEnumerator<T> GetEnumerator()
       {
              return this.Items.GetEnumerator();
       }

       #endregion

       #region IEnumerable Members

       System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
       {
              return this.Items.GetEnumerator();
       }

       #endregion
}




      NOTE: The Equals (object obj) method must be overridden in order for the group panel to
      work correctly!




www.windowsphonegeek.com
                                                                                                167
Silverlight for Windows Phone Toolkit in Depth




Basically we have a Title property of type string that will be used as a text in the group
items/headers.

Step2. Add the following DataTemplates to the page Resources section.
In the given example all cities are grouped by country name so as a result the group
headers/items contain the name of the country and below each group appear all the
information connected with this country. The XAML structure is as follows:

XAML

<phone:PhoneApplicationPage.Resources>
       <DataTemplate x:Key="groupHeaderTemplate">
              <Border Background="YellowGreen" Margin="6">
                     <TextBlock Text="{Binding Title}" FontSize="40"
Foreground="Black"/>
              </Border>
       </DataTemplate>
       <DataTemplate x:Key="groupItemTemplate" >
              <Border Background="YellowGreen" Width="99" Height="99"
Margin="6">
                     <TextBlock Text="{Binding Title}" FontSize="40"
Foreground="Black"/>
              </Border>
       </DataTemplate>
</phone:PhoneApplicationPage.Resources>



Step3. Define an instance of LongListSelector and add the previously declared DataTemplates in
this way:

XAML

<toolkit:LongListSelector x:Name="citiesListGropus" Background="Transparent"
            ItemTemplate="{StaticResource citiesItemTemplate}"
            ListHeaderTemplate="{StaticResource citiesListHeader}"
                ListFooterTemplate="{StaticResource citiesListFooter}"
            GroupHeaderTemplate="{StaticResource groupHeaderTemplate}"
            GroupItemTemplate="{StaticResource groupItemTemplate}" >
</toolkit:LongListSelector>



Step4. Adding the Group class to the Data Source
After we have defined the group class it’s time to add it to our data source. To do this we use a
LINQ expression so that we are able to add each group in the right place:




www.windowsphonegeek.com
                                                                                                    168
Silverlight for Windows Phone Toolkit in Depth




C#

var cityByCountry = from city in source
                       group city by city.Country into c
                       orderby c.Key
                       select new Group<City>(c.Key, c);



Step5. Finally set the ItemsSource of the LongListSelector in this way:

C#
this.citiesListGropus.ItemsSource = cityByCountry;




      NOTE: The sample data source is given at the beginning of this chapter. Take a look at it
      for reference.

Step6. Final result: here are some screen shots to see the result:




www.windowsphonegeek.com
                                                                                                  169
Silverlight for Windows Phone Toolkit in Depth




Customizing LongListSelector group popup

       NOTE: The default ItemsPanel of the LongListSelector is Vertical StackPanel.


This example demonstrates how to change the ItemsPanel of the LongListSelector with a
WrapPanel:

XAML

<toolkit:LongListSelector>
       <toolkit:LongListSelector.GroupItemsPanel>
              <ItemsPanelTemplate>
                     <toolkit:WrapPanel/>
              </ItemsPanelTemplate>
       </toolkit:LongListSelector.GroupItemsPanel>
</toolkit:LongListSelector>



After that the LongListSelector popup looks like:




www.windowsphonegeek.com
                                                                                        170
Silverlight for Windows Phone Toolkit in Depth




Animating LongListSelector group items using
transitions
The default implementation of the LongListSelector does not provide any appropriate property
or method for adding any kind of animation effects. However you can use the following events:
  GroupViewOpened - This event will be raised when the group popup's IsOpen property
     has been set to true.
  GroupViewClosing - This event will be raised when the group popup's IsOpen property
     has been set to false.

The easiest way even without writing any custom code is to use the toolkit`s transition
elements: RotateTransition, SlideTransition, SwivelTransition, TurnstileTransition,
RollTransition.
We will use TurnstileTransition for the opening popup animation and SwivelTransition for the
close popup animation. The next screen-shots demonstrate the final result:




This example uses the data binding implementation from the previous section. Basically we
have a class called “City” and a collection with data related to these cities.




www.windowsphonegeek.com
                                                                                                171
Silverlight for Windows Phone Toolkit in Depth




Step1. Implementing sample Grouping: The Group class is implemented as follows:

C#

public class Group<T> : IEnumerable<T>
{
       public Group(string name, IEnumerable<T> items)
       {
              this.Title = name;
              this.Items = new List<T>(items);
       }
       //additional code here
}



The LINQ query is:

C#

var cityByCountry = from city in source
                     group city by city.Country into c
                     orderby c.Key
                     select new Group<City>(c.Key, c);



Step2. Adding a LongListSelector with the necessary DataTemplates:

XAML

<toolkit:LongListSelector x:Name="citiesListGropus" Background="Transparent"
Grid.Row="1" ItemTemplate="{StaticResource citiesItemTemplate}"
GroupHeaderTemplate="{StaticResource groupHeaderTemplate}"
GroupItemTemplate="{StaticResource groupItemTemplate}" >
       <toolkit:LongListSelector.GroupItemsPanel>
              <ItemsPanelTemplate>
                     <toolkit:WrapPanel/>
              </ItemsPanelTemplate>
       </toolkit:LongListSelector.GroupItemsPanel>
</toolkit:LongListSelector>



Step3. Subscribe to the GroupViewOpened and GroupViewClosing event. The code is as
follows:
C#

this.citiesListGropus.GroupViewOpened += new
EventHandler<GroupViewOpenedEventArgs>(citiesListGropus_GroupViewOpened);
this.citiesListGropus.GroupViewClosing += new
EventHandler<GroupViewClosingEventArgs>(citiesListGropus_GroupViewClosing);




www.windowsphonegeek.com
                                                                                     172
Silverlight for Windows Phone Toolkit in Depth




Step4. Adding animation inside GroupViewOpened handler
The next thing we are going to do is to add some code in the GroupViewOpened event handler.
This handler takes a GroupViewOpenedEventArgs as a parameter. From this parameter you can
get a reference to the ItemsControl that holds all group items: e.ItemsControl. Once we have a
reference to the ItemsControl we can use ItemContainerGenerator in order to get the group
item container which is actually a UIElement. The code for accomplishing this is as follows:

C#

ItemContainerGenerator itemContainerGenerator = e.ItemsControl.ItemContainerGenerator;


Let’s create a TurnstileTransition with ForwardIn Mode and get the UIElements for each group
item:

C#
UIElement element = itemContainerGenerator.ContainerFromIndex(i) as UIElement;


After we have an instance of each element it is easy to add some animation to it using the
GetTransition (element) method. You can even add different animations to each element, the
choice is yours. The code is as follows:

C#

void citiesListGropus_GroupViewOpened(object sender, GroupViewOpenedEventArgs
e)
{
       ItemContainerGenerator itemContainerGenerator =
e.ItemsControl.ItemContainerGenerator;
       TurnstileTransition turnstileTransition = new TurnstileTransition();
       turnstileTransition.Mode = TurnstileTransitionMode.ForwardIn;

       int itemCount = e.ItemsControl.Items.Count;
       for (int i = 0; i < itemCount; i++)
       {
              UIElement element = itemContainerGenerator.ContainerFromIndex(i)
as UIElement;
              ITransition animation =
turnstileTransition.GetTransition(element);
              animation.Begin();
       }
}




www.windowsphonegeek.com
                                                                                                 173
Silverlight for Windows Phone Toolkit in Depth




This means that immediately after the group popup is opened each group element will be
animated using the TurnstileTransition effect.

      NOTE: You can use the ItemContainerGenerator to retrieve items based on their index or
     containers by specifying the data item. For example, if you have a data-bound
     ItemsControl, and you want to obtain an item based on its index, you can use the
ItemContainerGenerator.ContainerFromIndex method. If you want to retrieve the data item, use
ItemContainerGenerator.ItemFromContainer method.


Step5. Adding animation inside GroupViewClosing handler
Now, let’s focus on the GroupViewClosing handler. It takes GroupViewClosingEventArgs as a
parameter from where you can get a reference to the ItemsControl that holds all group items:
e.ItemsControl. In almost the same way we can get an instance of each group item container:

C#

ItemContainerGenerator itemContainerGenerator =
e.ItemsControl.ItemContainerGenerator;



But this time the situation is a little bit different. We will handle the event (e.Handled = true;)
and after that force the popup to close using the CloseGroupView() method. The reason for
doing this is the fact that if e.Handled is not set to True then the group is closing immediately
and no animation can be seen.
Each element is animated with SwivelTransition and when all animations have completed the
CloseGroupView() is called. The source code is as follows:

C#

void citiesListGropus_GroupViewClosing(object sender, GroupViewClosingEventArgs e)
{
       // set event as handled so that the group view is not closed right away
       // and the animations that we will start can be seen
       e.Cancel = true;

       SwivelTransition transition = new SwivelTransition();
       ItemContainerGenerator itemContainerGenerator =
e.ItemsControl.ItemContainerGenerator;

       int animationFinished = 0;
       int itemCount = e.ItemsControl.Items.Count;
       for (int i = 0; i < itemCount; i++)
       {
              UIElement element = itemContainerGenerator.ContainerFromIndex(i) as



www.windowsphonegeek.com
                                                                                                      174
Silverlight for Windows Phone Toolkit in Depth



UIElement;

               ITransition animation = transition.GetTransition(element);
               animation.Completed += delegate
               {
                      // close the group view when all animations have completed
                      if ((++animationFinished) == itemCount)
                      {
                             citiesListGropus.CloseGroupView();

                               //We have to scroll the to the selected group because we
have handled the event
                               citiesListGropus.ScrollToGroup(e.SelectedGroup);
                       }
               };
               animation.Begin();
       }
}




Dynamically Insert, Update and Delete data in a
data bound LongListSelector
Defining the Group<T> class
The Group<T> will inherit from ObservableCollection<T> so that the LongListSelector is notified
when the list of cities in a group changes:

C#

public class Group<T> : ObservableCollection<T>
{
       public Group(string name, IEnumerable<T> items)
       {
              this.Key = name;
              foreach (T item in items)
              {
                     this.Add(item);
              }
       }

       public override bool Equals(object obj)
       {
              Group<T> that = obj as Group<T>;

               return (that != null) && (this.Key.Equals(that.Key));
       }

       public string Key
       {



www.windowsphonegeek.com
                                                                                                  175
Silverlight for Windows Phone Toolkit in Depth



               get;
               set;
       }
}




Define EnumerableExtensions helper class
This class contains a convenience extension method that creates a new
ObservableCollection<T> given an IEnumerable<T>:

C#

public static class EnumerableExtensions
{
       public static ObservableCollection<T> ToObservableCollection<T>(this
IEnumerable<T> collection)
       {
              ObservableCollection<T> observableCollection = new
ObservableCollection<T>();
              foreach (T item in collection)
              {
                     observableCollection.Add(item);
              }

               return observableCollection;
       }
}




Defining the data source
The first thing we need to do is to define our model. We will use the following simple class
(presenting the Country/Language/City relation):

C#

public class City
{
       public string Name
       {
              get;
              set;
       }

       public string Country
       {
              get;
              set;
       }

       public string Language


www.windowsphonegeek.com
                                                                                               176
Silverlight for Windows Phone Toolkit in Depth



       {
               get;
               set;
       }
}




Next we will use a more complex way to define our data source (different than the approach
explained in our "in depth" series of posts):

C#

List<City> source = new       List<City>();
source.Add(new City() {       Name = "Madrid", Country = "ES", Language = "Spanish" });
source.Add(new City() {       Name = "Barcelona", Country = "ES", Language = "Spanish" });
source.Add(new City() {       Name = "Mallorca", Country = "ES", Language = "Spanish" });
source.Add(new City() {       Name = "Las Vegas", Country = "US", Language = "English" });

City item = new City() { Name = "Dallas", Country = "US", Language = "English" };
source.Add(item);

source.Add(new   City()   {   Name   =   "New York", Country = "US", Language = "English" });
source.Add(new   City()   {   Name   =   "London", Country = "UK", Language = "English" });
source.Add(new   City()   {   Name   =   "Mexico", Country = "MX", Language = "Spanish" });
source.Add(new   City()   {   Name   =   "Milan", Country = "IT", Language = "Italian" });
source.Add(new   City()   {   Name   =   "Roma", Country = "IT", Language = "Italian" });
source.Add(new   City()   {   Name   =   "Paris", Country = "FR", Language = "French" });




Polulating LongListSelector with data
First we add the following DataTemplates in the page resources:

XAML

<phone:PhoneApplicationPage.Resources>
      <!--The template for the list header.This will scroll as a part of the list -->
       <DataTemplate x:Key="citiesListHeader">
              <Border Background="Purple">
                     <StackPanel Orientation="Horizontal">
                            <TextBlock Text="Cities Header" />
                            <TextBlock Text ="{Binding Path=ItemsSource.Count,
ElementName=citiesListGropus}"/>
                     </StackPanel>
              </Border>
       </DataTemplate>
       <DataTemplate x:Key="citiesListFooter">
              <Border Background="Green">
                     <TextBlock Text="Cities Footer" />
              </Border>
       </DataTemplate>




www.windowsphonegeek.com
                                                                                                177
Silverlight for Windows Phone Toolkit in Depth



       <!-- The template for city items -->
       <DataTemplate x:Key="citiesItemTemplate">
              <StackPanel Grid.Column="1" VerticalAlignment="Top">
                     <TextBlock Text="{Binding Name}" FontSize="26" Margin="12,-
12,12,6"/>
                     <TextBlock Text="{Binding Country}" Foreground="GreenYellow"/>
                     <TextBlock Text="{Binding Language}" Foreground="Orange" />
              </StackPanel>
       </DataTemplate>

       <!-- The group header template, for groups in the main list -->
       <DataTemplate x:Key="groupHeaderTemplate">
              <Border Background="YellowGreen" Margin="6">
                     <TextBlock Text="{Binding Key}" FontSize="40"
Foreground="Black"/>
              </Border>
       </DataTemplate>

       <DataTemplate x:Key="groupItemTemplate" >
              <Border Background="YellowGreen" Width="99" Height="99" Margin="6">
                     <TextBlock Text="{Binding Key}" FontSize="40"
Foreground="Black"/>
              </Border>
       </DataTemplate>
</phone:PhoneApplicationPage.Resources>




Next we will create a new LongListSelector in XAML and will set its ListHeaderTemplate,
ListFooterTemplate, GroupHeaderTemplate, GroupItemTemplate as well as the
GroupItemsPanel property in this way:

XAML

<StackPanel Orientation="Vertical">
       <Button x:Name="btnAddGroup" Content="Add Group" Click="btnAddGroup_Click" />
       <Button x:Name="btnAddCity" Content="Add City" Click="btnAddCity_Click" />
       <Button x:Name="btnDeleteGroup" Content="Delete First Group"
Click="btnDeleteGroup_Click" />
</StackPanel>
<toolkit:LongListSelector x:Name="citiesListGropus" Background="Transparent"
Grid.Row="1"
ItemTemplate="{StaticResource citiesItemTemplate}"
ListHeaderTemplate="{StaticResource citiesListHeader}"
ListFooterTemplate="{StaticResource citiesListFooter}"
GroupHeaderTemplate="{StaticResource groupHeaderTemplate}"
GroupItemTemplate="{StaticResource groupItemTemplate}" >
       <toolkit:LongListSelector.GroupItemsPanel>
              <ItemsPanelTemplate>
                     <toolkit:WrapPanel/>
              </ItemsPanelTemplate>
       </toolkit:LongListSelector.GroupItemsPanel>
</toolkit:LongListSelector>




www.windowsphonegeek.com
                                                                                          178
Silverlight for Windows Phone Toolkit in Depth




Here is how we will set the ItemsSource of the LongListSelector control:

C#

var cityByCountry = from city in source
                    group city by city.Country into c
                    orderby c.Key
                    select new Group<City>(c.Key, c);

this.cityByCountryList = cityByCountry.ToObservableCollection();
this.citiesListGropus.ItemsSource = this.cityByCountryList;




      NOTE: While the cityByCountryList is of type IList<Group<City>> the actual type of the
      collection that this variable points to is ObservableCollection<Group<City>>. This is
      necessary so that the LongListSelector control is notified when the list of groups changes.


Dynamically Add new Groups in LongListSelector
Here is how you can dynamically add a new group to the LongListSelector:

C#

private void btnAddGroup_Click(object sender, RoutedEventArgs e)
{
       string deKey = "DE";
       List<City> deCities = new List<City>();
       deCities.Add(new City() { Country = deKey, Language = "German", Name =
"Berlin" });
       deCities.Add(new City() { Country = deKey, Language = "German", Name =
"Munich" });
       Group<City> deGroup = new Group<City>(deKey, deCities);

       this.cityByCountryList.Add(deGroup);
}


Dynamically Add new Items in LongListSelector
Here is how you can dynamically add an item to a group in the LongListSelector:

C#

private void btnAddCity_Click(object sender, RoutedEventArgs e)
{
       Group<City> firstGroup = this.cityByCountryList[0];
       City newCity = new City() { Country = firstGroup.Key, Language = "Spanish",
Name = "Valencia" };
       firstGroup.Add(newCity);
}



www.windowsphonegeek.com
                                                                                                    179
Silverlight for Windows Phone Toolkit in Depth




Dynamically Delete Items in LongListSelector
Here is how you can dynamically delete a group from the LongListSelector:

C#

private void btnDeleteGroup_Click(object sender, RoutedEventArgs e)
{
       this.cityByCountryList.RemoveAt(0);
}




www.windowsphonegeek.com
                                                                            180
Silverlight for Windows Phone Toolkit in Depth




MultiselectList
Overview
Basically, MultiselectList is an advanced ItemsControl that has a multiple selection mode that
allows users to select multiple items from a list. This is usually used in scenarios where the
same action has to be applied over multiple items.




Getting Started
To begin using MultiselectList first add a reference to the Microsoft.Phone.Controls.Toolkit.dll
assembly in your Windows Phone application project.

       NOTE: Microsoft.Phone.Controls.Toolkit.dll assembly is installed with the toolkit and you
       can find it in:
       For 32-bit systems:
       C:\Program Files\Microsoft SDKs\Windows
       Phone\v7.1\Toolkit\Aug11\Bin\Microsoft.Phone.Controls.Toolkit.dll
       For 64-bit systems:
       C:\Program Files (x86)\Microsoft SDKs\Windows
       Phone\v7.1\Toolkit\Aug11\Bin\Microsoft.Phone.Controls.Toolkit.dll



www.windowsphonegeek.com
                                                                                                   181
Silverlight for Windows Phone Toolkit in Depth




          Alternatively you can select it directly from the “...\Silverlight for Windows Phone Toolkit
          Source & Sample - Aug 2011\Bin\” if you have downloaded the “Silverlight for Windows
          Phone Toolkit Source & Sample - Aug 2011.zip” instead.

You can create an instance of the MultiselectList control either in XAML or with C#/VB.

         Define an instance of the MultiselectList control in XAML: you have to add the
          following namespace declaration:

xmlns:toolkit="clr-
namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"

XAML
<toolkit:MultiselectList>
       <toolkit:MultiselectItem Content="Item1"/>
       <toolkit:MultiselectItem Content="Item2"/>
       <toolkit:MultiselectItem Content="Item3"/>
</toolkit:MultiselectList>




         NOTE: Make sure that your page declaration includes the "toolkit" namespace! You can
         do this by using Visual Studio Toolbox, Expression Blend Designer or just include it on your
         own.

         Define an instance of the MultiselectList control in C#: just add the following using
          directive:

using Microsoft.Phone.Controls;

C#

MultiselectList list = new MultiselectList();
list.Items.Add(new MultiselectItem() { Content = "Item1"});
list.Items.Add(new MultiselectItem() { Content = "Item2" });
list.Items.Add(new MultiselectItem() { Content = "Item3" });




Key Properties
IsSelectionEnabled
IsSelectionEnabled is a dependency property of type bool. It gets or sets the flag that indicates
whether the list is in selection mode or not.




www.windowsphonegeek.com
                                                                                                         182
Silverlight for Windows Phone Toolkit in Depth




ItemInfoTemplate
ItemInfoTemplate is a dependency property of type DataTemplate. It gets or sets the data template
that is to be used on the item information field of the MultiselectItems.


ItemContainerStyle
ItemContainerStyle is a dependency property of type Style. It determines the Style that is
applied to the MultiselectList control items.


SelectedItems
SelectedItems is a read only property of type IList. It gets the collection of items that are currently
selected.

Key Events
SelectionChanged
Occurs when there is a change in the SelectedItems collection.
Example:
C#

multiselectList.SelectionChanged += new
SelectionChangedEventHandler(multiselectList_SelectionChanged);
void multiselectList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
       //...
}




IsSelectionEnabledChanged
Occurs when the value of the IsSelectionEnabled property has changed.
Example:
C#

multiselectList.IsSelectionEnabledChanged += new
DependencyPropertyChangedEventHandler(multiselectList_IsSelectionEnabledChanged);
void multiselectList_IsSelectionEnabledChanged(object sender,
DependencyPropertyChangedEventArgs e)
{
       //...
}




www.windowsphonegeek.com
                                                                                                          183
Silverlight for Windows Phone Toolkit in Depth




MultiselectItem
MultiselectItem represents a selectable item inside a MultiselectList.

      NOTE: A MultiselectList contains a collection of MultiselectItem objects. To select a
      MultiselectItem in a MultiselectList, set the IsSelected property to true. Bind a
      MultiselectItem to data by binding the ItemsSource property of a MultiselectList to a data
source.


MultiselectItem Key Properties & Events
IsSelected
IsSelected is a dependency property of type bool. It gets or sets the flag that indicates if the
item is currently selected.

HintPanelHeight
HintPanelHeight is a dependency property of type double. It gets or sets the height of the hint
panel.

ContentInfo
ContentInfo is a dependency property of type object. It gets or sets the content information for
the corresponding MultiselectItem.

ContentInfoTemplate
ContentInfoTemplate is a dependency property of type DataTemplate. It gets or sets the data
template that defines how the content information for the corresponding MultiselectItem is
displayed.

Selected
Occurs when the MultiselectItem is selected.

Example:
C#
multiselectItem.Selected += new RoutedEventHandler(multiselectItem_Selected);
//...
void multiselectItem_Selected(object sender, RoutedEventArgs e)
{
       //...
}




www.windowsphonegeek.com
                                                                                                   184
Silverlight for Windows Phone Toolkit in Depth




Unselected
Occurs when the MultiselectItem is unselected.
Example:
C#

multiselectItem.Unloaded += new RoutedEventHandler(multiselectItem_Unloaded);
//..
void multiselectItem_Unloaded(object sender, RoutedEventArgs e)
{
       //...
}




Data Binding MultiselectList
This example demonstrates how to populate the MultiselectList control with data using data
binding. In this example the MultiselectList control is used to enable the user to select multiple
ingredients from a list in order to create a custom pizza.

      Defining the Data Source
Here are the steps we will follow in order to create a data source:
Step1. Define the business/data class:
The first step is to define the data class. Let’s create a “PizzaOption” class which exposes the
following properties:

C#
public class PizzaOption
{
       public PizzaOption(string name)
       {
              this.Name = name;
       }

       public string Name
       {
              get;
              set;
       }

       public string Note
       {
              get;
              set;
       }




www.windowsphonegeek.com
                                                                                                     185
Silverlight for Windows Phone Toolkit in Depth



        public bool IsSelected
        {
               get;
               set;
        }
}


Step2. Create a sample collection with items of type TileItem:
C#
public MainPage()
{
   //...
 List<PizzaOption> pizzaOptions = new List<PizzaOption>()
 {
        new PizzaOption("Olives"),
        new PizzaOption("Mozzarella") { Note = "NEW"},
        new PizzaOption("Mushrooms"),
        new PizzaOption("Ham"),
        new PizzaOption("Bacon"),
        new PizzaOption("Pepperoni"),
        new PizzaOption("Salami") { Note = "SOON"},
        new PizzaOption("Tomatoes"),
        new PizzaOption("Onions")
 };
 //...
}


      Data binding the MultiselectList

Step1. Define a custom ItemTemplate in the page Resources.
XAML
<phone:PhoneApplicationPage.Resources>
       <DataTemplate x:Key="CustomItemTemplate">
                     <TextBlock Text="{Binding Name}" />
       </DataTemplate>
</phone:PhoneApplicationPage.Resources>


Step2. Define a custom ItemInfoTemplate in the page Resources.
XAML
<phone:PhoneApplicationPage.Resources>
       <DataTemplate x:Key="CustomItemInfoTemplate">
                     <TextBlock Text="{Binding Note}" />
       </DataTemplate>
</phone:PhoneApplicationPage.Resources>




www.windowsphonegeek.com
                                                                 186
Silverlight for Windows Phone Toolkit in Depth




Step3. Define a MultiselectList in XAML and set its ItemTemplate and ItemInfoTemplate:
XAML
<toolkit:MultiselectList Grid.Row="1" x:Name="multiSelectList" ItemTemplate="{StaticResource
CustomItemTemplate}" ItemInfoTemplate="{StaticResource CustomItemInfoTemplate}"/>


Step4. Set the MultiselectList ItemsSource
C#
ICollectionView pizzaOptionsCollectionView;

public MainPage()
{
       //...

       CollectionViewSource pizzaOptionSource = new CollectionViewSource();
       pizzaOptionSource.Source = pizzaOptions;
       this.pizzaOptionsCollectionView = pizzaOptionSource.View;
       using (this.pizzaOptionsCollectionView.DeferRefresh())
        {
              this.pizzaOptionsCollectionView.SortDescriptions.Add(new
       SortDescription("IsSelected", ListSortDirection.Descending));
              this.pizzaOptionsCollectionView.SortDescriptions.Add(new
       SortDescription("Name", ListSortDirection.Descending));
        }

       this.multiSelectList.ItemsSource = this.pizzaOptionsCollectionView;
}

The CollectionViewSource in the code above is used to sort the list by the values of the
IsSelected and Name properties.
Step5. Add the following ApplicationButtons in code behind:
C#
private ApplicationBarIconButton selectButton;
private ApplicationBarIconButton acceptButton;
private ApplicationBarIconButton cancelButton;
private ApplicationBarMenuItem selectAllMenuItem;
private ApplicationBarMenuItem unselectAllMenuItem;
// …
public MainPage()
{
       InitializeComponent();

       this.selectButton = new ApplicationBarIconButton();
       this.selectButton.IconUri = new Uri("/Toolkit.Content/ApplicationBar.Select.png",
UriKind.RelativeOrAbsolute);
       this.selectButton.Text = "select";
       this.selectButton.Click +=new EventHandler(selectButton_Click);

       this.acceptButton = new ApplicationBarIconButton();
       this.acceptButton.IconUri = new Uri("/Toolkit.Content/ApplicationBar.Check.png",
UriKind.RelativeOrAbsolute);



www.windowsphonegeek.com
                                                                                               187
Silverlight for Windows Phone Toolkit in Depth



       this.acceptButton.Text = "accept";
       this.acceptButton.Click +=new EventHandler(acceptButton_Click);

       this.cancelButton = new ApplicationBarIconButton();
       this.cancelButton.IconUri = new Uri("/Toolkit.Content/ApplicationBar.Cancel.png",
UriKind.RelativeOrAbsolute);
       this.cancelButton.Text = "cancel";
       this.cancelButton.Click += new EventHandler(cancelButton_Click);

       this.selectAllMenuItem = new ApplicationBarMenuItem();
       this.selectAllMenuItem.Text = "select all";
       this.selectAllMenuItem.Click += new EventHandler(selectAllMenuItem_Click);

       this.unselectAllMenuItem = new ApplicationBarMenuItem();
       this.unselectAllMenuItem.Text = "unselect all";
       this.unselectAllMenuItem.Click += new EventHandler(unselectAllMenuItem_Click);
}


Step6. Create a new method that will configure the application bar for the normal state:
C#
private void ShowNormalStateAppBar()
{
       this.ApplicationBar.Buttons.Clear();
       this.ApplicationBar.MenuItems.Clear();

       this.ApplicationBar.Buttons.Add(this.selectButton);

       this.pizzaOptionsCollectionView.Filter = this.IsSelectedFilter;
}


Step7. Call “ShowNormalStateAppBar” in the constructor of MainPage after
InitializeComponent():
C#
public MainPage()
{
    InitializeComponent();
    this.ShowNormalStateAppBar();
    //...
}


Step8. Subscribe to the MultiselectList IsSelectionEnabledChanged event and add the following
code in its handler:
C#
public MainPage()
{
    //...
    this.multiSelectList.IsSelectionEnabledChanged += new
DependencyPropertyChangedEventHandler(multiSelectList_IsSelectionEnabledChanged);
}



www.windowsphonegeek.com
                                                                                                188
Silverlight for Windows Phone Toolkit in Depth




C#
void multiSelectList_IsSelectionEnabledChanged(object sender,
DependencyPropertyChangedEventArgs e)
{
       if (this.multiSelectList.IsSelectionEnabled)
       {
              if (this.updateSelectedState)
              {
                     IEnumerable<PizzaOption> pizzaOptions =
this.pizzaOptionsCollectionView.SourceCollection as IEnumerable<PizzaOption>;
                     this.SetOptionsSelected(pizzaOptions, true, (pizzaOption) =>
pizzaOption.IsSelected);
              }
              this.ShowSelectionStateAppBar();
       }
       else
       {
              this.ShowNormalStateAppBar();
       }
}



      NOTE: It is important to handle the IsSelectionEnabledChanged event since selection mode
      can be triggered by user interaction also, and not only by setting the IsSelectionEnabled
      property.

Step9. Add a helper method that sets the IsSelected property of MultiselectItems:

C#
private void SetOptionsSelected(IEnumerable<PizzaOption> pizzaOptions, bool selected,
Predicate<PizzaOption> predicate)
{
       if (pizzaOptions == null)
       {
              return;
       }

       if (predicate == null)
       {
              predicate = (pizzaOption) => true;
       }

       ItemContainerGenerator itemContainerGenerator =
this.multiSelectList.ItemContainerGenerator;
       foreach (PizzaOption pizzaOption in pizzaOptions)
       {
              if (pizzaOption != null && predicate(pizzaOption))
              {
                     DependencyObject visualItem =
itemContainerGenerator.ContainerFromItem(pizzaOption);
                     MultiselectItem multiselectItem = visualItem as MultiselectItem;
                     if (multiselectItem != null)



www.windowsphonegeek.com
                                                                                                  189
Silverlight for Windows Phone Toolkit in Depth



                      {
               // NOTE: this will also add an item to the SelectedItems collection
                             multiselectItem.IsSelected = selected;
                      }
               }
       }
}


Step10. Create a method that will configure the application bar for the selection state:
C#
private void ShowSelectionStateAppBar()
{
       this.ApplicationBar.Buttons.Clear();
       this.ApplicationBar.MenuItems.Clear();

       this.ApplicationBar.Buttons.Add(this.acceptButton);
       this.ApplicationBar.Buttons.Add(this.cancelButton);

       this.ApplicationBar.MenuItems.Add(this.selectAllMenuItem);
       this.ApplicationBar.MenuItems.Add(this.unselectAllMenuItem);

       this.pizzaOptionsCollectionView.Filter = null;
}


Step11. Create a method that is used to filter the collection in the normal state so that only
selected items are displayed:
C#
private bool IsSelectedFilter(object item)
              {
                     PizzaOption pizzaOption = item as PizzaOption;
                     if (pizzaOption != null)
                     {
                            return pizzaOption.IsSelected;
                     }
                     return false;
              }


Step12. Override OnBackKeyPress and add the following code:
C#
protected override void OnBackKeyPress(CancelEventArgs e)
{
       base.OnBackKeyPress(e);
       if (this.multiSelectList.IsSelectionEnabled)
       {
              this.multiSelectList.IsSelectionEnabled = false;
              e.Cancel = true;
       }
}




www.windowsphonegeek.com
                                                                                                 190
Silverlight for Windows Phone Toolkit in Depth




Step13. Add the following code in the application buttons event handlers, defined in Step5:
C#
void cancelButton_Click(object sender, EventArgs e)
{
       this.multiSelectList.IsSelectionEnabled = false;
}

void acceptButton_Click(object sender, EventArgs e)
{
       IEnumerable<PizzaOption> pizzaOptions =
this.pizzaOptionsCollectionView.SourceCollection as IEnumerable<PizzaOption>;
       foreach (PizzaOption pizzaOption in pizzaOptions)
       {
              pizzaOption.IsSelected = false;
       }
       foreach (object item in this.multiSelectList.SelectedItems)
       {
              PizzaOption pizzaOption = item as PizzaOption;
              if (pizzaOption != null)
              {
                     pizzaOption.IsSelected = true;
              }
       }
       this.multiSelectList.IsSelectionEnabled = false;
}

void selectButton_Click(object sender, EventArgs e)
{
       this.multiSelectList.IsSelectionEnabled = true;
}

private bool updateSelectedState = true;

void unselectAllMenuItem_Click(object sender, EventArgs e)
{
       IEnumerable<PizzaOption> pizzaOptions =
this.pizzaOptionsCollectionView.SourceCollection as IEnumerable<PizzaOption>;
       this.SetOptionsSelected(pizzaOptions, false, null);

       // IMPORTANT NOTE:
       // when all items are unselected the selection mode automatically turns off
       // is this a bug???
       this.updateSelectedState = false;
       this.multiSelectList.IsSelectionEnabled = true;
       this.updateSelectedState = true;
}

void selectAllMenuItem_Click(object sender, EventArgs e)
{
       IEnumerable<PizzaOption> pizzaOptions =
this.pizzaOptionsCollectionView.SourceCollection as IEnumerable<PizzaOption>;
       this.SetOptionsSelected(pizzaOptions, true, null);
}




www.windowsphonegeek.com
                                                                                              191
Silverlight for Windows Phone Toolkit in Depth




Here is how the final result should look like:




www.windowsphonegeek.com
                                                 192
Silverlight for Windows Phone Toolkit in Depth




PhoneTextBox
Overview
Basically, PhoneTextBox is an advanced TextBox control with ActionIcon support, hints and
more. It exposes a set of properties for rich customization.




Getting Started
To begin using PhoneTextBox first add a reference to the Microsoft.Phone.Controls.Toolkit.dll
assembly in your Windows Phone application project.

       NOTE: Microsoft.Phone.Controls.Toolkit.dll assembly is installed with the toolkit and you
       can find it in:
       For 32-bit systems:
       C:\Program Files\Microsoft SDKs\Windows
       Phone\v7.1\Toolkit\Aug11\Bin\Microsoft.Phone.Controls.Toolkit.dll
       For 64-bit systems:
       C:\Program Files (x86)\Microsoft SDKs\Windows
       Phone\v7.1\Toolkit\Aug11\Bin\Microsoft.Phone.Controls.Toolkit.dll

       Alternatively you can select it directly from the “...\Silverlight for Windows Phone Toolkit
       Source & Sample - Aug 2011\Bin\” if you have downloaded the “Silverlight for Windows
       Phone Toolkit Source & Sample - Aug 2011.zip” instead.




www.windowsphonegeek.com
                                                                                                      193
Silverlight for Windows Phone Toolkit in Depth




You can create an instance of the PhoneTextBox control either in XAML or with C#/VB.

         Define an instance of the PhoneTextBox control in XAML: you have to add the
          following namespace declaration:

xmlns:toolkit="clr-
namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"

XAML

<toolkit:PhoneTextBox Hint="UserName"/>



         NOTE: Make sure that your page declaration includes the "toolkit" namespace! You can
         do this by using Visual Studio Toolbox, Expression Blend Designer or just include it on your
         own.

         Define an instance of the PhoneTextBox control in C#: just add the following using
          directive:

using Microsoft.Phone.Controls;

C#

PhoneTextBox textBox = new PhoneTextBox();
textBox.Hint = "UserName";




Key Properties
PhoneTextBox derives from TextBox so it has all properties of the TextBox plus the following
new ones:

Hint
Hint is a dependency property of type string. It gets or sets the Hint of the PhoneTextBox
control.


HintStyle
HintStyle is a dependency property of type Style. It gets or sets the Hint Style of the
PhoneTextBox control.




www.windowsphonegeek.com
                                                                                                        194
Silverlight for Windows Phone Toolkit in Depth




Example:
This example demonstrates how to add a simple HintStyle that changes only the FontFamily,
FontSize and Foreground properties without changing the whole ControlTemplate.
XAML
<phone:PhoneApplicationPage.Resources>
  <Style TargetType="ContentControl" x:Key="HintCustomStyle">
       <Setter Property="FontFamily" Value="Calibri"/>
       <Setter Property="Foreground" Value="Aqua"/>
       <Setter Property="FontSize" Value="30"/>
  </Style>
</phone:PhoneApplicationPage.Resources>

<!--...-->

<toolkit:PhoneTextBox Hint="Enter UserName" HintStyle="{StaticResource
HintCustomStyle}"/>




ActualHintVisibility
ActualHintVisibility is a dependency property of type Visibility. It gets or sets whether the hint is
actually visible.


LengthIndicatorVisible
LengthIndicatorVisible is a dependency property of type Boolean. It determines whether the
length indicator of the PhoneTextBox should be visible.


LengthIndicatorTheshold
LengthIndicatorTheshold is a dependency property of type int. It determines the threshold after
which the length indicator will appear.

Example:
XAML

<toolkit:PhoneTextBox Hint="Password" LengthIndicatorVisible="True"
LengthIndicatorTheshold="10" />




www.windowsphonegeek.com
                                                                                                        195
Silverlight for Windows Phone Toolkit in Depth




DisplayedMaxLength
DisplayedMaxLength is a dependency property of type int. It represents the displayed
maximum length of text that can be entered. This value takes priority over the MaxLength
property in the Length Indicator display.

Example:
XAML

<toolkit:PhoneTextBox Hint="Password" DisplayedMaxLength="4"
LengthIndicatorVisible="True"/>



       NOTE: In the given example you can enter more than 4 characters, but the length
       indicator displays the number of characters entered out of 4, even if the length of the text
       entered is greater than 4.




ActionIcon
ActionIcon is a dependency property of type ImageSource. It gets or sets the ActionIcon image
of the PhoneTextBox control.
Example1:
XAML

<toolkit:PhoneTextBox Hint="Search" ActionIcon="/Images/Search.png"
ActionIconTapped="Search_ActionIconTapped"/>




www.windowsphonegeek.com
                                                                                                      196
Silverlight for Windows Phone Toolkit in Depth




C#

private void Search_ActionIconTapped(object sender, EventArgs e)
        {
           //do some action here. I.e open MessageBox, etc.
           MessageBox.Show("The action icon was tapped!");
        }




Example2:
XAML

<toolkit:PhoneTextBox Hint="Password" ActionIcon="wpglogo.png"/>




Key Events
ActionIconTapped
Occurs when the ActionIcon is tapped.
Example:
C#

phoneTextBox.ActionIconTapped += new EventHandler(phoneTextBox_ActionIconTapped);
//...
void phoneTextBox_ActionIconTapped(object sender, EventArgs e)
{
       //...
}




www.windowsphonegeek.com
                                                                                    197
Silverlight for Windows Phone Toolkit in Depth




PerformanceProgressBar
Overview
Basically, PerformanceProgressBar is an animated indeterminate progress bar, which is used in
situations where the extent of the task is unknown or the progress of the task cannot be
determined in a way that could be expressed as a percentage or similar. This bar uses animated
dots to show that progress is taking place, rather than using the size of the filled portion to
show the total amount of progress. It is actually the well known PerformanceProgressBar
provided by Jeff Wilcox, which uses the compositor thread exclusively for animation, instead of
the UI (user interface) thread.




PerformanceProgressBar is a kind of progress bar implementation for a smoother appearance
of the indeterminate states, with the added behavior that after the behavior is no longer
needed, it smoothly fades out the dots for a less jarring experience. No exposed Value
property. Important - this control is not intended for regular progress bar use, but only
indeterminate. As a result, only an IsIndeterminate set of visual states are defined in the nested
progress bar template. Use the standard ProgressBar control in the platform for determinate
scenarios as there is no performance benefit in determinate mode. For example it can be very
useful when implementing an animated splash screen.

      NOTE: One of the reasons that this is so important is that performance is always an issue
      when there is a progress bar visible (whether you're parsing data, processing layout
      changes, or performing network requests), so any issues with bogging down the user
interface thread will be more obvious.


       NOTE: PerformanceProgressBar is different from the standard ProgressBar. There is an
       unfortunate performance issue with the default way the PerformanceBar is constructed in
       the WP7 SDK. To achieve the effect of the dots flying across the screen the standard
control actually uses 5 slider controls (where the thumb of the slider is actually styled to be the
dots). This generates a lot of work for the UI thread, when in actual fact we want to off load
tasks such as animation to the Compositor thread wherever possible and leave the UI thread for
things like layout passes and our application logic. (reference: Tips for ProgressBar )



www.windowsphonegeek.com
                                                                                                      198
Silverlight for Windows Phone Toolkit in Depth




Getting Started
To begin using PerformanceProgressBar first add a reference to the
Microsoft.Phone.Controls.Toolkit.dll assembly in your Windows Phone application project.

        NOTE: Microsoft.Phone.Controls.Toolkit.dll assembly is installed with the toolkit and you
        can find it in:
        For 32-bit systems:
        C:\Program Files\Microsoft SDKs\Windows
        Phone\v7.1\Toolkit\Aug11\Bin\Microsoft.Phone.Controls.Toolkit.dll
        For 64-bit systems:
        C:\Program Files (x86)\Microsoft SDKs\Windows
        Phone\v7.1\Toolkit\Aug11\Bin\Microsoft.Phone.Controls.Toolkit.dll

        Alternatively you can select it directly from the “...\Silverlight for Windows Phone Toolkit
        Source & Sample - Aug 2011\Bin\” if you have downloaded the “Silverlight for Windows
        Phone Toolkit Source & Sample - Aug 2011.zip” instead.

You can create a PerformanceProgressBar instance either in XAML or with C#/VB.

       Define a PerformanceProgressBar instance in XAML: you have to add the following
        namespace declaration (for example):

xmlns:toolkit="clr-
namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"

Here is an example of how to use a PerformanceProgressBar declared in XAML. We will use a
CheckBox to show/hide the progress bar (the IsIndeterminate is bound to the IsChecked).

XAML

<CheckBox Content="Show PerformanceProgressBar" IsChecked="{Binding
IsIndeterminate, ElementName=performanceProgressBar, Mode=TwoWay}"/>
<toolkit:PerformanceProgressBar x:Name="performanceProgressBar"/>




       NOTE: Make sure that your page declaration includes the "toolkit" namespace! You can
       do this by using Visual Studio Toolbox, Expression Blend Designer or just include it on your
       own.




www.windowsphonegeek.com
                                                                                                       199
Silverlight for Windows Phone Toolkit in Depth




         Define a PerformanceProgressBar instance in C#: just add the following using directive:

using Microsoft.Phone.Controls;

C#

PerformanceProgressBar performancePrgressbar = new PerformanceProgressBar ();
performancePrgressbar.IsIndeterminate = true;




         NOTE: If choosing to add this control via C# code then do not forget to associate it to a
         panel on your page for example: this.ContentPanel.Children.Add(performancePrgressbar);



Key Properties

ActualIsIndeterminate
This is a dependency property of type bool. It gets or sets the value indicating whether the
actual indeterminate property should be reflecting a particular value.

IsIndeterminate
This is a dependency property of type bool. It gets or sets a value indicating whether the control
is in the indeterminate state.

         NOTE: The property responsible for the color of the animation effect is "Foreground"!



XAML

<toolkit:PerformanceProgressBar x:Name="performanceProgressBarCustomized"
Foreground="Red" Background="Red" IsIndeterminate="True"/>




www.windowsphonegeek.com
                                                                                                     200
Silverlight for Windows Phone Toolkit in Depth




Transitions
Overview
Basically, Transitions are a kind of animation framework that provides different animations. It
helps users to add some attractive visual effects to their apps and implement some typical
Windows Phone animations which are a key part of the Metro experience.




Key concepts
Transition animations are based on a set of classes and interfaces that enable you to use
transitions in different scenarios (animating all kinds of UIElements) and at the same time
enables you implement your own custom animations that can be used with the rest of the API.


www.windowsphonegeek.com
                                                                                                  201
Silverlight for Windows Phone Toolkit in Depth




TransitionElement
This is an abstract class which is actually a transition factory for a particular transition family. It
has an abstract method GetTransition(UIElement element) which creates a new ITransition for
the specified UIElement. There are five built-in TransitionElements:

    RotateTransition
    SlideTransition
    SwivelTransition
    TurnstileTransition
    RollTransition is different from the rest because it does not expose a Mode property.

The Mode property enables you to select which specific transition you want (except for
RollTransition). There are enums for each transition family to choose a mode:
  RotateTransitionMode - contains some basic values connected with the rotation
     animation like rotation angle in degrees.
  SlideTransitionMode - contains values connected with the slide animation like the
     direction of the effect: up, down, left, right etc.
  SwivelTransitionMode - contains values connected with the Swivel animation like swivel:
     forward in, backward out, full screen in, etc.
  TurnstileTransitionMode - contains values connected with the Turnstile animation like
     turnstile: forward in, backward out, etc.


ITransition
The ITransition interface is probably the most important part of the transition framework. It
controls the behavior of transitions. By implementing this interface you can create your own
custom animation that performs whatever animation effect you prefer. It provides all the API
that you need for implementing an animation. Here is a list of the exposed methods:
  Begin() - Initiates the set of animations associated with the ITransition.
  GetCurrentState() - Gets the ClockState of the ITransition.
  GetCurrentTime() - Gets the current time of the ITransition.
  Pause() - Pauses the animation clock associated with the ITransition.
  Resume() - Resumes the animation clock, or run-time state, associated with the
     ITransition.
  Seek() - Moves the ITransition to the specified animation position. The ITransition
     performs the requested seek when the next clock tick occurs.




www.windowsphonegeek.com
                                                                                                          202
Silverlight for Windows Phone Toolkit in Depth




        SeekAlignedToLastTick() - Moves the ITransition to the specified animation position
         immediately (synchronously).
        SkipToFill() - Advances the current time of the ITransition's clock to the end of its active
         period.
        Stop() - Stops the ITransition.

         NOTE: If you are familiar with the Storyboard in Silverlight then here is the place to say
         that ITransition is pretty similar to the storyboard interface.


NavigationTransition
This class has navigation in/out TransitionElements for the designer experiences. It exposes two
dependency properties of type TransitionElement:
  Backward: Gets or sets the backward NavigationTransition.
  Forward: Gets or sets the forward NavigationTransition.

NavigationTransition exposes the following events:
 BeginTransition: indicates that the navigation transition will begin.
 EndTransition: indicates that the navigation transition has ended.


     NOTE: In the toolkit you can find two
     classes NavigationInTransition and NavigationOutTransition which are subclasses of
NavigationTransition.


TransitionService
This is one of the basic static classes in the transition framework. It exposes two attached
properties for navigation.

          NavigationInTransition: NavigationInTransitionProperty is a static attached property of
           type NavigationInTransition you can get/set its value as follows:

C#

TransitionService.GetNavigationInTransition(element);
TransitionService.SetNavigationInTransition(element);



          NavigationOutTransition: NavigationOutTransitionProperty is a static attached property
           of type NavigationOutTransition you can get/set its value as follows:


www.windowsphonegeek.com
                                                                                                        203
Silverlight for Windows Phone Toolkit in Depth




C#

TransitionService.GetNavigationOutTransition(element);
TransitionService.SetNavigationOutTransition(element);




      NOTE: If you have any animation when transitioning to a page, then when clicking the
      back button it is preferable from the UX point of view to have the reverse animation or at
      least some different animation.


TransitionFrame
The TransitionFrame class enables navigation transitions for PhoneApplicationPages.

      NOTE: Do not forget to set your application's RootFrame property to an instance
      of TransitionFrame (in App.InitializePhoneApplication of the App.xaml.cs) if you want to
      have automatically animated Page transitions.


C#
RootFrame = new TransitionFrame();




Getting Started
To begin using Transitions first add a reference to the Microsoft.Phone.Controls.Toolkit.dll
assembly in your Windows Phone application project.

       NOTE: Microsoft.Phone.Controls.Toolkit.dll assembly is installed with the toolkit and you
       can find it in:
       For 32-bit systems:
       C:\Program Files\Microsoft SDKs\Windows
       Phone\v7.1\Toolkit\Aug11\Bin\Microsoft.Phone.Controls.Toolkit.dll
       For 64-bit systems:
       C:\Program Files (x86)\Microsoft SDKs\Windows
       Phone\v7.1\Toolkit\Aug11\Bin\Microsoft.Phone.Controls.Toolkit.dll

       Alternatively you can select it directly from the “...\Silverlight for Windows Phone Toolkit
       Source & Sample - Aug 2011\Bin\” if you have downloaded the “Silverlight for Windows
       Phone Toolkit Source & Sample - Aug 2011.zip” instead.




www.windowsphonegeek.com
                                                                                                      204
Silverlight for Windows Phone Toolkit in Depth




You can create Transitions in XAML or C#/VB.

         Define Transitions in XAML: you have to add the following namespace declaration (for
          example):

xmlns:toolkit="clr-
namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"

XAML

<toolkit:TransitionService.NavigationInTransition>
       <toolkit:NavigationInTransition>
              <toolkit:NavigationInTransition.Backward>
                     <toolkit:TurnstileTransition Mode="BackwardIn"/>
              </toolkit:NavigationInTransition.Backward>
              <toolkit:NavigationInTransition.Forward>
                     <toolkit:TurnstileTransition Mode="ForwardIn"/>
              </toolkit:NavigationInTransition.Forward>
       </toolkit:NavigationInTransition>
</toolkit:TransitionService.NavigationInTransition>
<toolkit:TransitionService.NavigationOutTransition>
       <toolkit:NavigationOutTransition>
              <toolkit:NavigationOutTransition.Backward>
                     <toolkit:TurnstileTransition Mode="BackwardOut"/>
              </toolkit:NavigationOutTransition.Backward>
              <toolkit:NavigationOutTransition.Forward>
                     <toolkit:TurnstileTransition Mode="ForwardOut"/>
              </toolkit:NavigationOutTransition.Forward>
       </toolkit:NavigationOutTransition>
</toolkit:TransitionService.NavigationOutTransition>




         NOTE: Make sure that your page declaration includes the "toolkit" namespace! You can
         do this by using Visual Studio Toolbox, Expression Blend Designer or just include it on your
         own.

         Define Transitions in C#: just add the following using directive:

using Microsoft.Phone.Controls;

C#

TurnstileTransition turnstileTransition = new TurnstileTransition { Mode =
TurnstileTransitionMode.BackwardIn};
NavigationInTransition navInTransition = new NavigationInTransition();
navInTransition.Backward = turnstileTransition;
turnstileTransition.Mode = TurnstileTransitionMode.ForwardIn;
navInTransition.Forward = turnstileTransition;
NavigationOutTransition navOutTransition = new NavigationOutTransition();
turnstileTransition.Mode = TurnstileTransitionMode.BackwardOut;



www.windowsphonegeek.com
                                                                                                        205
Silverlight for Windows Phone Toolkit in Depth



navOutTransition.Backward = turnstileTransition;
turnstileTransition.Mode = TurnstileTransitionMode.ForwardOut;
navOutTransition.Forward = turnstileTransition;
PhoneApplicationPage phoneApplicationPage =
(PhoneApplicationPage)(((PhoneApplicationFrame)Application.Current.RootVisual)).Content
;




Page Transition
This is the case when we switch between different pages with transition effect using Page
Navigation. The important things in this scenario are:
  Do not forget to set your application's RootFrame property to an instance
      of TransitionFrame (in App.InitializePhoneApplication of the App.xaml.cs) if you want to
      have automatically animated Page transitions.
  You can use NavigationInTransition that let you specify backward and forward transitions
      for in Page navigations.
  You can use NavigationOutTransition that let you specify backward and forward
      transitions for out Page navigations.
  NavigationInTransition and NavigationOutTransition are useful only when we have Page
      Navigation.
  You can reference the PhoneApplicationPage in this way :


C#

PhoneApplicationPage phoneApplicationPage =
(PhoneApplicationPage)(((PhoneApplicationFrame)Application.Current.RootVisual)).Content;



You can use transitions when navigating between different pages. The code for accomplishing
this is as follows:

Step1. Set your application's RootFrame property to an instance of TransitionFrame (in
App.InitializePhoneApplication of the App.xaml.cs) if you want to have automatically animated
Page transitions:

C#

private void InitializePhoneApplication()
{
       if (phoneApplicationInitialized)
              return;

       // Create the frame but don't set it as RootVisual yet; this allows the


www.windowsphonegeek.com
                                                                                                 206
Silverlight for Windows Phone Toolkit in Depth



splash
         // screen to remain active until the application is ready to render.
         RootFrame = new TransitionFrame();
         RootFrame.Navigated += CompleteInitializePhoneApplication;

         // Handle navigation failures
         RootFrame.NavigationFailed += RootFrame_NavigationFailed;

         // Ensure we don't initialize again
         phoneApplicationInitialized = true;
}




Step2. Add the following code whenever you want to start the transition effect.

C#

RotateTransition rotatetransition = new RotateTransition();
rotatetransition.Mode = RotateTransitionMode.In90Clockwise;

PhoneApplicationPage phoneApplicationPage =
(PhoneApplicationPage)(((PhoneApplicationFrame)Application.Current.RootVisual)).Content
;

ITransition transition = rotatetransition.GetTransition(phoneApplicationPage);
transition.Completed += delegate {transition.Stop(); };
transition.Begin();




UIElement Transition
This is the case when we want to animate some UIElements like for example: TextBox, Button,
ListBox etc. Usually this is done by creating a Transition and ITransition instances.
Having in mind that GetTransition method accepts UIElement as a parameter, then we could
use the built in animations to make transitions between different UIElements. All you need to
do is to change the code in this way:

C#

TextBox tbx = new TextBox();
ITransition transition = rotatetransition.GetTransition(tbx );
transition.Completed += delegate { transition.Stop(); };
transition.Begin();




www.windowsphonegeek.com
                                                                                                207
Silverlight for Windows Phone Toolkit in Depth




      NOTE: Handling of the Completed event is optional and it depends on the specified
      animation.



Custom Transitions

      NOTE: One of the most important parts of the custom implementation is the ITransition
      interface.

When implementing some custom functionality usually you can choose more than one
approach. In this case I will demonstrate three different ways of making custom Transitions.

Transition Structure
Generally each Transition consists of the following elements:
  The base class that implement ITransition interface - when implementing this interface
     you will have to add some functionality that handles Begin/End of the animation and
     Completed event handler.
  A class that derives from TransitionElement - overriding GetTransition(UIElement
     element) is the key point in this class.
  Storyboard animation - this creates storyboard animation; it can be either a XAML file or
     C# code.
Here is how the CustomTransition class which implements ITransition looks like:

C#

public class CustomTransition : ITransition
{
       Storyboard storyboard;
       public CustomTransition(Storyboard sb)
       {
              storyboard = sb;
       }

       #region ITransition Members

       public void Begin()
       {
              storyboard.Begin();
       }

       public event EventHandler Completed
       {
              add
              {



www.windowsphonegeek.com
                                                                                               208
Silverlight for Windows Phone Toolkit in Depth



                         storyboard.Completed += value;
                }
                remove
                {
                         storyboard.Completed -= value;
                }
          }
          // more code
}




        NOTE: CustomTransition class is used when calling GetTransition(UIElement element)for
        each custom implementation. Do not forget to implement the Completed event handler as
        well!


CustomTransition with XAML animation
The first transition that I will demonstrate is a simple Roll like animation that changes the
PlaneProjection.RotationZ of the element. The steps are as follows:

       Create the animation
     Step1. Create a Storyboards folder in the root of your project.
     Step2. Add a ResourceDictionary and name it Transition1.xaml.
     Step3. Add the Storyboard animation in the Transition1.xaml (make sure that its build
action is set to Resource)
The final code should look like the following:

XAML

<Storyboard
xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml” >
       <DoubleAnimationUsingKeyFrames
Storyboard.TargetProperty=”(UIElement.Projection).(PlaneProjection.RotationZ)”>
              <EasingDoubleKeyFrame KeyTime=”0” Value=”0”>
                     <EasingDoubleKeyFrame.EasingFunction>
                            <ExponentialEase EasingMode=”EaseIn” Exponent=”1”/>
                     </EasingDoubleKeyFrame.EasingFunction>
              </EasingDoubleKeyFrame>
              <EasingDoubleKeyFrame KeyTime=”0:0:0.3” Value=”45”>
                     <EasingDoubleKeyFrame.EasingFunction>
                            <ExponentialEase EasingMode=”EaseOut”
Exponent=”15”/>
                     </EasingDoubleKeyFrame.EasingFunction>
              </EasingDoubleKeyFrame>
              <EasingDoubleKeyFrame KeyTime=”0:0:0.6” Value=”45”/>
       </DoubleAnimationUsingKeyFrames>


www.windowsphonegeek.com
                                                                                                209
Silverlight for Windows Phone Toolkit in Depth



</Storyboard>


        Create a Transiton1.cs class which is actually your new custom transition
     Step1. Add a new class called Transition1.cs that derives from TransitionElement
     Step2. We will have to add some code in order to get the storyboard from the
Transition1.xaml file. This is done using StreamResourceInfo and XamlReader.

C#

private static Dictionary<string, string> storyboardXamlCache;
private static Storyboard GetStoryboard(string name)
{
       if (storyboardXamlCache == null)
       {
              storyboardXamlCache = new Dictionary<string, string>();
       }
       string xaml = null;
       if (storyboardXamlCache.ContainsKey(name))
       {
              xaml = storyboardXamlCache[name];
       }
       else
       {
              string path = "/WP7TransitionsDemo;component/Storyboards/" + name
+ ".xaml";
              Uri uri = new Uri(path, UriKind.Relative);
              StreamResourceInfo streamResourceInfo =
Application.GetResourceStream(uri);
              using (StreamReader streamReader = new
StreamReader(streamResourceInfo.Stream))
              {
                     xaml = streamReader.ReadToEnd();
                     storyboardXamlCache[name] = xaml;
              }
       }
       return XamlReader.Load(xaml) as Storyboard;
}



          Override GetTransition(UIElement element)

Override the GetTransition(UIElement element) method and return an instance of
CustomTransition. It is important to add a PlaneProjection to the element because our
storyboard animates the PlaneProjection.RotationZ value. Once you get a reference to the
storyboard you will have to set its target element. The code is as follows:




www.windowsphonegeek.com
                                                                                           210
Silverlight for Windows Phone Toolkit in Depth




C#

public override ITransition GetTransition(UIElement element)
{
    Storyboard myStoryboard = GetStoryboard("transition1");
    PlaneProjection projection = new PlaneProjection()
    {
       CenterOfRotationX = 0.0
    };
    projection.SetValue(FrameworkElement.NameProperty, "projection");
    if (element.Projection == null)
       {
           element.Projection = projection;
       }
    Storyboard.SetTarget(myStoryboard, element);
    return new CustomTransition(myStoryboard);
}


    Use the newly created Transition1
That is all, now you have a custom transition Transition1. You can use it for example to animate
a button in this way:
C#

Transition1 transition1 = new Transition1();
ITransition transition = transition1.GetTransition(this.btnTransition1);
//transition.Completed += delegate
// {
//   transition.Stop();
// };
transition.Begin();




      NOTE: Handling of the Completed event is optional and it depends on the specified
      animation!


CustomTransition with C# animation
In this section I will show you how to implement a simple Fade animation using only C#. The
steps are as follows:
   Create a Transiton2.cs class that derives from TransitionElement : this is actually your
      new custom transition and all the code in placed here.
   Create a method called CreateStoryboard in the Transition2.cs that will create the
      animation




www.windowsphonegeek.com
                                                                                                   211
Silverlight for Windows Phone Toolkit in Depth




    Override GetTransition(UIElement element): Override the GetTransition(UIElement
     element) method and return an instance of CustomTransition. Once you get a reference
     to the storyboard you will have to set its target element. The final code is as follows:

C#

public class Transition2: TransitionElement
{
 public override ITransition GetTransition(UIElement element)
   {
       Storyboard myStoryboard = CreateStoryboard(1.0,0.0);
       Storyboard.SetTarget(myStoryboard, element);
       return new CustomTransition(myStoryboard);
   }

 private Storyboard CreateStoryboard(double from, double to)
  {
      Storyboard result = new Storyboard();
      DoubleAnimation animation = new DoubleAnimation();
      animation.From = from;
      animation.To = to;
      Storyboard.SetTargetProperty(animation, new
PropertyPath(UIElement.OpacityProperty));
      result.Children.Add(animation);
      return result;
   }
}




      NOTE: This is a simple opacity animation that will hide the animated element.


    Use the newly created Transition2
That is all, now you have a custom transition Transition2. You can use it for example to animate
a button in this way:
C#

Transition2 transition2 = new Transition2();
ITransition transition = transition2.GetTransition(this.btnTransition2);
//transition.Completed += delegate { transition.Stop(); };
transition.Begin();




www.windowsphonegeek.com
                                                                                                   212
Silverlight for Windows Phone Toolkit in Depth




      NOTE: Handling of the Completed event is optional and depends on the specified
      animation!


CustomTransition with animation defined in the
NavigationInTransition/NavigationOutTransition
In this part I will show you how to implement a simple Fade animation that is defined in the
Page NavigationOutTransition section. In the previous two examples I demonstrated the
UIElement Transitions, so now it is time for the Page Transition. The steps are as follows:
   Create a Transiton3 class that derives from TransitionElement which is actually your new
      custom transition and all the code in placed here.
   Create a dependency property called Animation of type Storyboard this property will be
      used later in order to add the newly created storyboard to the NavigationOutTransition
      of the page.
   Override the GetTransition(UIElement element) method and return an instance of
      CustomTransition. Once you get a reference to the storyboard you will have to set its
      target element. The final code is as follows:

C#

public class Transition3 : TransitionElement
{
       public static readonly DependencyProperty AnimationProperty =
DependencyProperty.Register(
              "Animation", typeof(Storyboard), typeof(Transition3), null);

       public Storyboard Animation
       {
              get
              {
                     return (Storyboard)GetValue(AnimationProperty);
              }
              set
              {
                     SetValue(AnimationProperty, value);
              }
       }

       public override ITransition GetTransition(UIElement element)
       {
              Storyboard.SetTarget(this.Animation, element);
              return new CustomTransition(this.Animation);
       }
}




www.windowsphonegeek.com
                                                                                               213
    Silverlight for Windows Phone Toolkit in Depth




        Define the storyboard in the Page NavigationOutTransition section as follows:

    XAML

    <toolkit:TransitionService.NavigationOutTransition>
           <toolkit:NavigationOutTransition>
                  <toolkit:NavigationOutTransition.Forward>
                         <local:Transition3>
                                <local:Transition3.Animation>
                                       <Storyboard>
                                              <DoubleAnimation
    Storyboard.TargetProperty="Opacity" From="1.0" To="0.3" Duration="0:0:2"/>
                                       </Storyboard>
                                </local:Transition3.Animation>
                         </local:Transition3>
                  </toolkit:NavigationOutTransition.Forward>
           </toolkit:NavigationOutTransition>
    </toolkit:TransitionService.NavigationOutTransition>


    Create a sample Page1 to which to navigate to
    Using the newly created Transition3
     That is all, now you have a custom transition Transition3. The animation if fired automatically
     when you NavigateOut of the Page.

    C#
    NavigationService.Navigate(new Uri("/Page1.xaml", UriKind.Relative));



           NOTE: Do not forget to set your application's RootFrame property to an instance
           of TransitionFrame (in App.InitializePhoneApplication of the App.xaml.cs) if you want to
           have automatically animated Page transitions.




    www.windowsphonegeek.com
                                                                                                       214
Silverlight for Windows Phone Toolkit in Depth




TiltEffect
Overview
Generally, TiltEffect enables you to add additional visual feedback for control interaction.
Instead of having standard pressed or un-pressed states, controls with the tilt effect provide
motion during manipulation. The result is a "tilt" like response when the control is touched.

When a control is tapped, the TiltEffect class will search for specified controls that have the tilt
effect enabled. By default, the general ButtonBase class and ListBoxItem controls are specified
as tiltable items. If a control type were not present here, the tilt effect would not be applied to
any controls even if the IsTiltEnabled dependency property is attached and set to True.




Getting Started
To begin using TiltEffect first add a reference to the Microsoft.Phone.Controls.Toolkit.dll
assembly in your Windows Phone application project.

       NOTE: Microsoft.Phone.Controls.Toolkit.dll assembly is installed with the toolkit and you
       can find it in:
       For 32-bit systems:
       C:\Program Files\Microsoft SDKs\Windows
       Phone\v7.1\Toolkit\Aug11\Bin\Microsoft.Phone.Controls.Toolkit.dll
       For 64-bit systems:
       C:\Program Files (x86)\Microsoft SDKs\Windows
       Phone\v7.1\Toolkit\Aug11\Bin\Microsoft.Phone.Controls.Toolkit.dll

       Alternatively you can select it directly from the “...\Silverlight for Windows Phone Toolkit
       Source & Sample - Aug 2011\Bin\” if you have downloaded the “Silverlight for Windows
       Phone Toolkit Source & Sample - Aug 2011.zip” instead.




www.windowsphonegeek.com
                                                                                                       215
Silverlight for Windows Phone Toolkit in Depth




You can enable the IsTiltEffect property to a control either in XAML or in C#/VB.

         Define TiltEffect in XAML: you have to add the following namespace declaration (for
          example):

xmlns:toolkit="clr-
namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"

XAML
<ToggleButton Content="Button" toolkit:TiltEffect.IsTiltEnabled="True"/>




         NOTE: Make sure that your page declaration includes the "toolkit" namespace! You can
         do this by using Visual Studio Toolbox, Expression Blend Designer or just include it on your
         own.

         Define TiltEffect in C#: just add the following using directive:

using Microsoft.Phone.Controls;

C#
this.button.SetValue(TiltEffect.IsTiltEnabledProperty,true);




         NOTE: In order to apply a TiltEffect to a control, its control type has to be defined in the
         TiltableItems collection.




www.windowsphonegeek.com
                                                                                                        216
Silverlight for Windows Phone Toolkit in Depth




Key Properties
TiltableItems
This is a static property of type List<Type> that represents default list of items that are tiltable.

IsTiltEnabled
This is a static dependency property of type bool that determines whether the tilt effect is
enabled on a container (and all its children).

SuppressTilt
This is a static dependency property of type bool that suppresses the tilt effect on a single
control that would otherwise be tilted.




How to Enable TiltEffect globally
In order to enable the TiltEffect to all controls inside a particular page just set
toolkit:TiltEffect.IsTiltEnabled="True" at the top of the page:

XAML

<phone:PhoneApplicationPage
    x:Class="WP7ToolkitTest.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-
namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"



www.windowsphonegeek.com
                                                                                                        217
Silverlight for Windows Phone Toolkit in Depth



    shell:SystemTray.IsVisible="True"     xmlns:toolkit="clr-
namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"
toolkit:TiltEffect.IsTiltEnabled="True" >



After that just add some controls to the page and you will see the effect in action:

XAML

<StackPanel x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
       <Button Content="Button"/>
       <CheckBox Content="CheckBox"/>
       <TextBlock Text="ListBox:"/>
       <ListBox>
              <ListBoxItem Content="Item1"/>
              <ListBoxItem Content="Item2"/>
              <ListBoxItem Content="Item3"/>
       </ListBox>
       <ToggleButton Content="ToggleButton"/>
</StackPanel>




How to Suppress TiltEffect
You can suppress the tilt effect by simply setting the SuppressTilt to true:

XAML

<ListBox toolkit:TiltEffect.IsTiltEnabled="True">
       <ListBoxItem Content="Item1"/>
       <ListBoxItem Content="Item2" toolkit:TiltEffect.SuppressTilt="True"/>
       <ListBoxItem Content="Item3"/>
       <ListBoxItem Content="Item4"/>
</ListBox>




www.windowsphonegeek.com
                                                                                       218
Silverlight for Windows Phone Toolkit in Depth




Adding more controls to TiltableItems
In order to add TiltEffect support for additional controls you should update the
TiltableItems list from your own code like for example:

C#

public MainPage()
{
       InitializeComponent();
       TiltEffect.TiltableItems.Add(typeof(MenuItem));
}




XAML

<toolkit:ContextMenuService.ContextMenu>
       <toolkit:ContextMenu >
              <toolkit:MenuItem toolkit:TiltEffect.IsTiltEnabled="true"
Header="Item1" />
              <toolkit:MenuItem toolkit:TiltEffect.IsTiltEnabled="true"
Header="Item2" />
       </toolkit:ContextMenu>
</toolkit:ContextMenuService.ContextMenu>




       NOTE: If a control type were not present in the TiltableItems collection, the tilt effect
       would not be applied to any controls even if the IsTiltEnabled dependency property is
       attached and set to True.


Adding TiltEffect to data bound ListPicker Items
In order to add TiltEffect support for the ListPickerItem you should update the TiltableItems list
like for example:

C#

public MainPage()
{
    InitializeComponent();
    this.list.ItemsSource = new List<string>
{"FirstItem","SecondItem","ThirdItem" };
    TiltEffect.TiltableItems.Add(typeof(ListPickerItem));
}




www.windowsphonegeek.com
                                                                                                     219
Silverlight for Windows Phone Toolkit in Depth




XAML

<toolkit:ListPicker x:Name="list" toolkit:TiltEffect.IsTiltEnabled="true">
       <toolkit:ListPicker.ItemTemplate>
              <DataTemplate>
                     <TextBlock Text="{Binding}"/>
              </DataTemplate>
       </toolkit:ListPicker.ItemTemplate>
</toolkit:ListPicker>




www.windowsphonegeek.com
                                                                             220
Silverlight for Windows Phone Toolkit in Depth




TimePicker
Overview
 Basically, Windows Phone Toolkit`s TimePicker is an UI element that will automatically provide
you with a TextBox input and when the user selects it, the picker will display a form where you
can choose a time value using infinite scrolling. TimePicker is UX control that fits in the
Windows Phone Design Guidelines.




Getting Started
To begin using TimePicker first add a reference to the Microsoft.Phone.Controls.Toolkit.dll
assembly in your Windows Phone application project.

       NOTE: Microsoft.Phone.Controls.Toolkit.dll assembly is installed with the toolkit and you
       can find it in:
       For 32-bit systems:
       C:\Program Files\Microsoft SDKs\Windows
       Phone\v7.1\Toolkit\Aug11\Bin\Microsoft.Phone.Controls.Toolkit.dll
       For 64-bit systems:
       C:\Program Files (x86)\Microsoft SDKs\Windows
       Phone\v7.1\Toolkit\Aug11\Bin\Microsoft.Phone.Controls.Toolkit.dll

       Alternatively you can select it directly from the “...\Silverlight for Windows Phone Toolkit
       Source & Sample - Aug 2011\Bin\” if you have downloaded the “Silverlight for Windows
       Phone Toolkit Source & Sample - Aug 2011.zip” instead.


www.windowsphonegeek.com
                                                                                                      221
Silverlight for Windows Phone Toolkit in Depth




You can create a TimePicker instance either in XAML or C#/VB.

         Define a TimePicker instance in XAML: you have to add the following namespace
          declaration (for example):

xmlns:toolkit="clr-
namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"

XAML
<toolkit:TimePicker x:Name="timePicker"/>




         NOTE: Make sure that your page declaration includes the "toolkit" namespace! You can
         do this by using Visual Studio Toolbox, Expression Blend Designer or just include it on your
         own.

         Define a TimePicker instance in C#: just add the following using directive:

using Microsoft.Phone.Controls;

C#
TimePicker timePicker = new TimePicker();



         NOTE: If choosing to add this control via C# code then do not forget to associate it to a
         panel on your page for example: this.ContentPanel.Children.Add(timePicker);


IMPORTANT: To see the correct ApplicationBar icons in the DatePicker and TimePicker, you will
need to create a folder in the root of your project called "Toolkit.Content" and put the icons in
there. The toolkit provides the necessary icons, but you have to copy them from the
PhoneToolkitSample project. They must be named "ApplicationBar.Cancel.png" and
"ApplicationBar.Check.png", and the build action must be "Content"!




www.windowsphonegeek.com
                                                                                                        222
Silverlight for Windows Phone Toolkit in Depth




Key Properties

Header
Header is a dependency property of type object. It gets or sets the header of the control.
Example:
XAML
<toolkit:TimePicker x:Name="timePicker" Header="TimePicker"        Value="12:40"/>



HeaderTemplate
HeaderTemplate is a dependency property of type DataTemplate. It gets or sets the template
used to display the control's header.

PickerPageUri
PickerPageUri is a dependency property of type Uri. It gets or sets the Uri to use for loading the
IDateTimePickerPage instance when the control is clicked. Check the below "Customizing the
full-screen picker page" section for more info and detailed example.

Value
Value is a dependency property of type “DateTime?”. It gets or sets the DateTime value.




www.windowsphonegeek.com
                                                                                                     223
Silverlight for Windows Phone Toolkit in Depth




Example:
XAML
<toolkit:TimePicker x:Name="timePicker"          Header="TimePicker"       Value="12:40"/>



ValueString
ValueString is a dependency property of type string. It gets the string representation of the
selected value.
Example:
C#
this.textBlock.Text = timePicker.ValueString;



ValueStringFormat
ValueStringFormat is a dependency property of type string. It gets or sets the format string to
use when converting the Value property to a string. For more information about the different
format strings you can visit the MSDN documentation.


       NOTE: Format strings include "{" and "}" so if you want to use them in XAML you have to escape
       the special characters. For example: ValueStringFormat="{}{0:T}".




So if you want to change the format used to display the date/time initial buttons you can use
either XAML or C#:
Example:
XAML
<toolkit:TimePicker x:Name="timePicker"          ValueStringFormat="{}{0:T}"/>

Or
C#
this.timePicker.ValueStringFormat = "{0:T}";


In both cases the displayed result is: 8:05:00 AM




www.windowsphonegeek.com
                                                                                                        224
Silverlight for Windows Phone Toolkit in Depth




Key Events
ValueChanged
Event that is invoked when the Value property changes.

C#

this.timePicker.ValueChanged += new
EventHandler<DateTimeValueChangedEventArgs>(picker_ValueChanged);
//...


void picker_ValueChanged(object sender, DateTimeValueChangedEventArgs e)
{
    DateTime date = (DateTime)e.NewDateTime;
    this.textBlock.Text = date.ToString("d");
}




Customizing the full-screen picker page
You can customize the full-screen picker page by setting the DatePicker.PickerPageUri or
TimePicker.PickerPageUri property to point to a PhoneApplicationPage that implements the
IDateTimePickerPage interface. IDateTimePickerPage represents an interface for
DatePicker/TimePicker to use for communicating with a picker page. It consists of only
one property:

C#

public interface IDateTimePickerPage
{
       /// <summary>
       /// Gets or sets the DateTime to show in the picker page and to set when
the user makes a selection.
       /// </summary>
       DateTime? Value
       {
              get;
              set;
       }
}



Let’s create a sample scenario with a custom page that reset the selected value of the
DatePicker to DateTime.Now. The steps for accomplishing this are as follows:


www.windowsphonegeek.com
                                                                                           225
Silverlight for Windows Phone Toolkit in Depth




Step1. Add a sample Windows Phone Partial Page to your project and rename it to
"CustomPage".

Step2. In the code behind implement IDateTimePickerPage interface. The code is as follows:

C#

public partial class CustomPage : PhoneApplicationPage, IDateTimePickerPage
{
       public CustomPage()
       {
              InitializeComponent();
       }

       #region IDateTimePickerPage Members

       public DateTime? Value
       {
              get;
              set;
       }

       #endregion
}



Step3. After that add a button to the "CustomPage". The code is:

XAML

<Border BorderBrush="Red" Background="Orange" Height="200" Width="300">
       <Button Content="DateTime Now" x:Name="btn" Click="btn_Click"/>
</Border>



Step4. The next step is to add some code behind that will set the selected value of the
DatePicker to DateTime.Now. The code is:

C#

private void btn_Click(object sender, RoutedEventArgs e)
{
       // set date and close picker
       Value = DateTime.Now;
       NavigationService.GoBack();
}



Step5. Set the PickerPageUri to "/DatePickerDemo;component/CustomPage.xaml", the code is:



www.windowsphonegeek.com
                                                                                             226
Silverlight for Windows Phone Toolkit in Depth




XAML

<toolkit:DatePicker x:Name="datePicker1" Header="Custom DatePicker"
Value="2/3/2010"
PickerPageUri="/DatePickerDemo;component/CustomPage.xaml" />



Step6. Here is the result




That is all you need to do in order to have a custom full screen picker page. If you run the
example you will see that when you select the DatePicker our newly created "CustomPage"
page will appear. After that when you press the button NavigationService.GoBack(); is called
and the value of the DatePicker is updated with the current date time. Just so simply you can
implement your own custom full screen page and add whatever you prefer there.




www.windowsphonegeek.com
                                                                                                227
Silverlight for Windows Phone Toolkit in Depth




ToggleSwitch
Overview
Basically, ToggleSwitch is an UI element that enables users to turn something on or off. It is the
Windows Phone equivalent of the well known checkbox and has two check states: On and Off.




Getting Started
To begin using ToggleSwitch first add a reference to the Microsoft.Phone.Controls.Toolkit.dll
assembly in your Windows Phone application project.

       NOTE: Microsoft.Phone.Controls.Toolkit.dll assembly is installed with the toolkit and you
       can find it in:
       For 32-bit systems:
       C:\Program Files\Microsoft SDKs\Windows
       Phone\v7.1\Toolkit\Aug11\Bin\Microsoft.Phone.Controls.Toolkit.dll
       For 64-bit systems:
       C:\Program Files (x86)\Microsoft SDKs\Windows
       Phone\v7.1\Toolkit\Aug11\Bin\Microsoft.Phone.Controls.Toolkit.dll

       Alternatively you can select it directly from the “...\Silverlight for Windows Phone Toolkit
       Source & Sample - Aug 2011\Bin\” if you have downloaded the “Silverlight for Windows
       Phone Toolkit Source & Sample - Aug 2011.zip” instead.

You can create a ToggleSwitch instance either in XAML or C#/VB.

      Define a ToggleSwitch instance in XAML: you have to add the following namespace
       declaration (for example):

xmlns:toolkit="clr-
namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"

XAML


www.windowsphonegeek.com
                                                                                                      228
Silverlight for Windows Phone Toolkit in Depth




<toolkit:ToggleSwitch x:Name="toggle" Content="ToggleSwitch is on"
IsChecked="True" Header="ToggleSwitch"/>




         NOTE: Make sure that your page declaration includes the "toolkit" namespace! You can
         do this by using Visual Studio Toolbox, Expression Blend Designer or just include it on your
         own.

         Define a ToggleSwitch instance in C#: just add the following using directive:
using Microsoft.Phone.Controls;

C#

ToggleSwitch toggleSwitch = new ToggleSwitch();




         NOTE: If choosing to add this control via C# code then do not forget to associate it to a
         panel on your page for example: this.ContentPanel.Children.Add(toggleSwitch);



Key Properties

IsChecked
IsChecked is a dependency property of type Nullable<bool>. It gets or sets whether the
ToggleSwitch is checked.

Example:
XAML

<toolkit:ToggleSwitch x:Name="toggle" Content="ToggleSwitch is on"
IsChecked="True" Header="ToggleSwitch"/>




Header
Header is a dependency property of type object. It gets or sets the header of the
ToggleSwitch.




www.windowsphonegeek.com
                                                                                                        229
Silverlight for Windows Phone Toolkit in Depth




Content
An object that contains the control's content.
Example:
XAML

<toolkit:ToggleSwitch x:Name="toggle" Content="ToggleSwitch is on"
IsChecked="True" Header="ToggleSwitch"/>




HeaderTemplate
HeaderTemplate is a dependency property of type DataTemplate. It gets or sets the template
used to display the control's header.

ContentTemplate
The data template that is used to display the content of the ToggleSwitch.

Example:
XAML

<toolkit:ToggleSwitch Header="5:45 AM">
       <toolkit:ToggleSwitch.HeaderTemplate>
              <DataTemplate>
                     <ContentControl Foreground="{StaticResource
PhoneForegroundBrush}" Content="{Binding}"/>
              </DataTemplate>
              </toolkit:ToggleSwitch.HeaderTemplate>
              <toolkit:ToggleSwitch.ContentTemplate>
                     <DataTemplate>
                            <StackPanel>
                                   <StackPanel Orientation="Horizontal">
                                          <TextBlock Text="Alarm: "
FontSize="{StaticResource PhoneFontSizeSmall}"/>
                                          <ContentControl
HorizontalAlignment="Left" FontSize="{StaticResource PhoneFontSizeSmall}"
Content="{Binding}"/>
                                   </StackPanel>
                                   <TextBlock Text="every schoolday"
FontSize="{StaticResource PhoneFontSizeSmall}" Foreground="{StaticResource
PhoneSubtleBrush}"/>
                            </StackPanel>
                     </DataTemplate>
              </toolkit:ToggleSwitch.ContentTemplate>
</toolkit:ToggleSwitch>




www.windowsphonegeek.com
                                                                                             230
Silverlight for Windows Phone Toolkit in Depth




SwitchForeground
SwitchForeground is a dependency property of type Brush. It gets or sets the switch foreground
color of the ToggleSwitch.

Example:
C#
this.toggle.SwitchForeground = new SolidColorBrush(Colors.Red);




Key Events
Checked
Occurs when the ToggleSwitch is checked.
Example:
C#

this.toggle.Checked += new EventHandler<RoutedEventArgs>(toggle_Checked);
//...
void toggle_Checked(object sender, RoutedEventArgs e)
{
       //add some code here
}




Click
Occurs when the ToggleSwitch is clicked.
Example:
C#

this.toggle.Click += new EventHandler<RoutedEventArgs>(toggle_Click);
//...
void toggle_Click(object sender, RoutedEventArgs e)
{
       //add some codehere
}




www.windowsphonegeek.com
                                                                                                 231
Silverlight for Windows Phone Toolkit in Depth




Indeterminate
Occurs when the ToggleSwitch is indeterminate - neither on nor off
Example:
C#

this.toggle.Indeterminate += new
EventHandler<RoutedEventArgs>(toggle_Indeterminate);
//...
void toggle_Indeterminate(object sender, RoutedEventArgs e)
{
       //add some code here
}




Unchecked
Occurs when the ToggleSwitch is unchecked.
Example:
C#

this.toggle.Unchecked += new EventHandler<RoutedEventArgs>(toggle_Unchecked);
//...
void toggle_Unchecked(object sender, RoutedEventArgs e)
{
       //add some code here
}




Dynamically Changing ToggleSwitch Content
depending on the current State
This example demonstrates how to dynamically change the Content of the ToggleSwitch
depending on the current State: On or Off.

Step1. Define an instance of ToggleSwitch and set IsChecked property to true:

XAML

<toolkit:ToggleSwitch x:Name="toggle" Content="ToggleSwitch is on"
IsChecked="True" Header="ToggleSwitch"/>




www.windowsphonegeek.com
                                                                                      232
Silverlight for Windows Phone Toolkit in Depth




Step2. Subscribe to “Checked” and “Unchecked” handlers of the ToggleSwitch and add the
following code inside:

C#

public MainPage()
{
    InitializeComponent();
    this.toggle.Checked += new EventHandler<RoutedEventArgs>(toggle_Checked);
    this.toggle.Unchecked += new
EventHandler<RoutedEventArgs>(toggle_Unchecked);
}

void toggle_Unchecked(object sender, RoutedEventArgs e)
{
    this.toggle.Content = "ToggleSwitch is off";
    this.toggle.SwitchForeground = new SolidColorBrush(Colors.Red);
}

void toggle_Checked(object sender, RoutedEventArgs e)
{
    this.toggle.Content = "ToggleSwitch is on";
    this.toggle.SwitchForeground = new SolidColorBrush(Colors.Green);
}




The result can be seen on the following screen shots:




www.windowsphonegeek.com
                                                                                         233
Silverlight for Windows Phone Toolkit in Depth




WrapPanel
Overview
Basically, WrapPanel is a panel that enables users to position child elements sequentially from
left to right or top to bottom. When elements extend beyond the panel edge, they are
positioned in the next row or column.

      NOTE: A WrapPanel contains a collection of UIElement objects, which are in the Children
      collection!

In the most common scenario WrapPanel as the name suggests will wrap the child controls, any
controls which cannot fit on the first line/column will be wrapped to next line/column and so
forth.




Getting Started
To begin using WrapPanel first add a reference to the Microsoft.Phone.Controls.Toolkit.dll
assembly in your Windows Phone application project.

       NOTE: Microsoft.Phone.Controls.Toolkit.dll assembly is installed with the toolkit and you
       can find it in:
       For 32-bit systems:
       C:\Program Files\Microsoft SDKs\Windows
       Phone\v7.1\Toolkit\Aug11\Bin\Microsoft.Phone.Controls.Toolkit.dll
       For 64-bit systems:
       C:\Program Files (x86)\Microsoft SDKs\Windows
       Phone\v7.1\Toolkit\Aug11\Bin\Microsoft.Phone.Controls.Toolkit.dll


www.windowsphonegeek.com
                                                                                                   234
Silverlight for Windows Phone Toolkit in Depth




          Alternatively you can select it directly from the “...\Silverlight for Windows Phone Toolkit
          Source & Sample - Aug 2011\Bin\” if you have downloaded the “Silverlight for Windows
          Phone Toolkit Source & Sample - Aug 2011.zip” instead.


You can create a WrapPanel instance either in XAML or C#/VB.

         Define a WrapPanel instance in XAML: you have to add the following namespace
          declaration (for example):

xmlns:toolkit="clr-
namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"

XAML

<toolkit:WrapPanel ItemHeight="100" ItemWidth="100" Height="300">
       <Rectangle Fill="Aqua" Height="80" Width="80"/>
       <Rectangle Fill="Pink" Height="80" Width="80"/>
       <Rectangle Fill="Green" Height="80" Width="80"/>
       <Rectangle Fill="YellowGreen" Height="80" Width="80"/>
       <Rectangle Fill="Red" Height="80" Width="80"/>
</toolkit:WrapPanel>




         NOTE: Make sure that your page declaration includes the "toolkit" namespace! You can
         do this by using Visual Studio Toolbox, Expression Blend Designer or just include it on your
         own.

         Define a WrapPanel instance in C#: just add the following using directive:

using Microsoft.Phone.Controls;

C#

WrapPanel wrapPanel = new WrapPanel();
wrapPanel.ItemHeight = 80;
wrapPanel.ItemWidth = 80;
Rectangle rect1 = new Rectangle() {Fill = new SolidColorBrush(Colors.Blue)};
Rectangle rect2 = new Rectangle() {Fill = new SolidColorBrush(Colors.Green)};
Rectangle rect3 = new Rectangle() {Fill = new SolidColorBrush(Colors.Purple)};

wrapPanel.Children.Add(rect1);
wrapPanel.Children.Add(rect2);
wrapPanel.Children.Add(rect3);




www.windowsphonegeek.com
                                                                                                         235
Silverlight for Windows Phone Toolkit in Depth




       NOTE: If choosing to add this control via C# code then do not forget to associate it to a
       panel on your page for example: this.ContentPanel.Children.Add(wrapPanel);


Key Properties
ItemHeight
ItemHeight is a dependency property of type double. Gets or sets the height of the layout area
for each item that is contained in a WrapPanel. The default value is Double.NaN.

ItemWidth
ItemWidth is a dependency property of type double. Gets or sets the width of the layout area
for each item that is contained in a WrapPanel. The default value is Double.NaN.

Orientation
Orientation is a dependency property of type Orientation. Gets or sets the direction in which
child elements are arranged. The default is System.Windows.Controls.Orientation.Horizontal.


Horizontal WrapPanel
This example demonstrates how to use WrapPanel in Horizontal Orientation mode. We will
arrange 5 items in a WrapPanel. The code is as follows:

XAML

<toolkit:WrapPanel ItemHeight="100" ItemWidth="100" Height="300">
       <Rectangle Fill="Aqua" Height="80" Width="80"/>
       <Rectangle Fill="Pink" Height="80" Width="80"/>
       <Rectangle Fill="Green" Height="80" Width="80"/>
       <Rectangle Fill="YellowGreen" Height="80" Width="80"/>
       <Rectangle Fill="Red" Height="80" Width="80"/>
</toolkit:WrapPanel>




www.windowsphonegeek.com
                                                                                                   236
Silverlight for Windows Phone Toolkit in Depth




Vertical WrapPanel
This example demonstrates how to use WrapPanel in Vertical Orientation mode. We will
arrange 5 items in a WrapPanel. The code is as follows:

XAML

<toolkit:WrapPanel ItemHeight="100" ItemWidth="100" Orientation="Vertical"
Height="300">
       <Rectangle Fill="WhiteSmoke" Height="80" Width="80"/>
       <Rectangle Fill="White" Height="80" Width="80"/>
       <Rectangle Fill="Beige" Height="80" Width="80"/>
       <Rectangle Fill="Bisque" Height="80" Width="80"/>
       <Rectangle Fill="Wheat" Height="80" Width="80"/>
</toolkit:WrapPanel>




WrapPanel as ItemsPanel
Although WrapPanel is a simple component it can be used in advanced scenarios when you
want to change the ItemsPanel of any particular items control. For example you can use it in
the LongListSelector, ListPicker, ListBox and other ItemsControls in order to arrange the items in
a suitable way:




www.windowsphonegeek.com
                                                                                                     237
Silverlight for Windows Phone Toolkit in Depth




Example1: ListBox populated with ListBoxItems and WrapPanel set as ItemsPanel.

XAML
<ListBox>
       <ListBox.ItemsPanel>
              <ItemsPanelTemplate>
                     <toolkit:WrapPanel ItemWidth="100" ItemHeight="50"/>
              </ItemsPanelTemplate>
       </ListBox.ItemsPanel>
       <ListBoxItem Content="Item1"/>
       <ListBoxItem Content="Item2"/>
       <ListBoxItem Content="Item3"/>
       <ListBoxItem Content="Item4"/>
       <ListBoxItem Content="Item5"/>
       <ListBoxItem Content="Item6"/>
</ListBox>

Example2: ListBox data bound to a collection of strings and WrapPanel set as ItemsPanel.
XAML
<ListBox x:Name="listBox">
   <ListBox.ItemsPanel>
       <ItemsPanelTemplate>
          <toolkit:WrapPanel ItemWidth="150" ItemHeight="150"/>
       </ItemsPanelTemplate>
   </ListBox.ItemsPanel>
   <ListBox.ItemTemplate>
      <DataTemplate>
         <Border Background="YellowGreen" Height="150" Width="150" Margin="5" >
         <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center"
Text="{Binding}"/>
         </Border>
     </DataTemplate>
   </ListBox.ItemTemplate>
</ListBox>



C#
this.listBox.ItemsSource = new List<string>() { "Item1", "Item2", "Item3", "Item4",
"Item5"};

Here is how the result should look like:




www.windowsphonegeek.com
                                                                                           238
Silverlight for Windows Phone Toolkit in Depth




Additional Components
In Windows Phone Toolkit August 2011 release Microsoft also added some additional
components and helper classes that can make developing Windows Phone 7.1 applications
easier.

RecurringDaysPicker
Represents a control that allows the user to choose days of the week. Basically, it is a simple
control that derives from ListPicker and does not expose any additional public properties.




Example:
XAML

<toolkit:RecurringDaysPicker Header="Days" FullModeHeader="FullMode"/>




www.windowsphonegeek.com
                                                                                                  239
Silverlight for Windows Phone Toolkit in Depth




HeaderedItemsControl
Basically, HeaderedItemsControl represents an ItemsControl that contains multiple items and
has a header. It exposes the following public properties:


Header
Header is a dependency property of type object. It gets or sets the item that labels the control.
The default value is null.

HeaderTemplate
HeaderTemplate is a dependency property of type DataTemplate. It gets or sets a data
template that is used to display the contents of the control's header.

ItemContainerStyle
ItemContainerStyle is a dependency property of type Style. It gets or sets the style that is
applied to the container element generated for each item.


DateTimeConverters
In the below examples it is assumed that DateTime Now is 8/21/2011.


       NOTE: To use DateTimeConverters in XAML you will have to add the following namespace
       declaration (for example):
xmlns:toolkit="clr-
namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"




RelativeTimeConverter
Converts a DateTime object into a string that represents the elapsed time relatively to the
present.
Example:
XAML

<phone:PhoneApplicationPage.Resources>
        <toolkit:RelativeTimeConverter x:Key="RelativeTimeConverter"/>
</phone:PhoneApplicationPage.Resources>
<!--...-->




www.windowsphonegeek.com
                                                                                                    240
Silverlight for Windows Phone Toolkit in Depth



<toolkit:DatePicker x:Name="datepicker" Value="8/21/2011" />
<TextBlock Text="RelativeTimeConverter:" />
<TextBlock Text="{Binding ElementName=datepicker, Path=Value,
Converter={StaticResource RelativeTimeConverter}}" />




DailyDateTimeConverter
Converts a DateTime object into a string appropriately formatted for daily feeds.
Example:
XAML

<phone:PhoneApplicationPage.Resources>
        <toolkit:DailyDateTimeConverter x:Key="DailyDateTimeConverter"/>
</phone:PhoneApplicationPage.Resources>
<!--...-->

<toolkit:DatePicker x:Name="datepicker" Value="8/21/2011" />
<TextBlock Text="DailyDateTimeConverter:" />
<TextBlock Text="{Binding ElementName=datepicker, Path=Value,
Converter={StaticResource DailyDateTimeConverter}}" />




FullViewDateTimeConverter
Converts a DateTime object into a string appropriately formatted to display full date and time
information. This format can usually be found in email.

       NOTE: This format never displays the year.




www.windowsphonegeek.com
                                                                                                 241
Silverlight for Windows Phone Toolkit in Depth




HourlyDateTimeConverter
Converts a DateTime object into a string appropriately formatted for hourly feeds. This format
can usually be found in messaging.
Example:
XAML

<phone:PhoneApplicationPage.Resources>
        <toolkit:HourlyDateTimeConverter x:Key="HourlyDateTimeConverter"/>
</phone:PhoneApplicationPage.Resources>
<!--...-->

<toolkit:DatePicker x:Name="datepicker" Value="8/21/2011" />
<TextBlock Text="HourlyDateTimeConverter:" />
<TextBlock Text="{Binding ElementName=datepicker, Path=Value,
Converter={StaticResource HourlyDateTimeConverter}}" />




ListViewDateTimeConverter
Converts a DateTime object into a string appropriately formatted for list-views. This format can
usually be found in email.

       NOTE: This format never displays the year.



Example:
XAML

<phone:PhoneApplicationPage.Resources>
        <toolkit:ListViewDateTimeConverter x:Key="ListViewDateTimeConverter"/>
</phone:PhoneApplicationPage.Resources>
<!--...-->

<toolkit:DatePicker x:Name="datepicker" Value="8/21/2011" />
<TextBlock Text="ListViewDateTimeConverter:" />
<TextBlock Text="{Binding ElementName=datepicker, Path=Value,
Converter={StaticResource ListViewDateTimeConverter}}" />




www.windowsphonegeek.com
                                                                                                   242
Silverlight for Windows Phone Toolkit in Depth




ThreadDateTimeConverter

Converts a DateTime object into a string appropriately formatted for threads. This format can
be found in messaging.

       NOTE: This format never displays the year.


Example:
XAML

<phone:PhoneApplicationPage.Resources>
        <toolkit:ThreadDateTimeConverter x:Key="ThreadDateTimeConverter"/>
</phone:PhoneApplicationPage.Resources>
<!--...-->

<toolkit:DatePicker x:Name="datepicker" Value="8/21/2011" />
<TextBlock Text="ThreadDateTimeConverter:" />
<TextBlock Text="{Binding ElementName=datepicker, Path=Value,
Converter={StaticResource ThreadDateTimeConverter}}" />




www.windowsphonegeek.com
                                                                                                243
Silverlight for Windows Phone Toolkit in Depth




LocalizedResources
Windows Phone Toolkit August 2011 includes the following resources (mainly date time strings)
localized in 22 languages:




www.windowsphonegeek.com
                                                                                                244
Silverlight for Windows Phone Toolkit in Depth




Reference:

           1. Windows Phone Development on MSDN: http://msdn.microsoft.com/en-
              us/library/ff402535%28v=vs.92%29.aspx
           2. Silverlight for Windows Phone Toolkit official Codeplex page:
              http://silverlight.codeplex.com/
           3. www.windowsphonegeek.com




www.windowsphonegeek.com
                                                                                 245

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:181
posted:5/13/2012
language:English
pages:245