Creating Compelling Content with XAML for Windows Store Apps: Control Templates, ListView,ListBox, Customization, and a Game Title Screen

I’m finding development for Windows* 8 to be a lot of fun.  Over the last year, I have created a children’s math game and have written a few blogs for it:

UI Element touch physics:

Writing your own collision handler:

Game FPS and the DispatcherTimer:


Here in this blog, I talk about how I added a cool-looking title screen to my game by modifying some control templates.  You can read about control templates here:


My goal was to design my title screen primarily with XAML and minimal code behind (C#).  I also wanted to ensure that the XAML markup was robust, rather than hardcoded.  This is where binding came in.  You can read about binding in XAML here:


So, I started by creating a title screen with the default black backdrop and a title header.  I proceeded to adding a ListView control at bottom.  Now, the purpose of this control was to list the various menu options.  Rather than hardcode each individual menu option in XAML, I specified the ItemsSource for the control using the “empty binding” declaration {Binding}.  This binds to the object specified by the inherited DataContext.  I then specify the DataContext in the code behind (C#) as follows:


public ObservableCollection<String> menu_items;

        protected override void OnNavigatedTo(NavigationEventArgs e)


            menu_items = new ObservableCollection<string>();

            menu_items.Add("Start game");




            this.DataContext = menu_items;



Figure 1: Code Behind Menu Construction**


The following link talks about binding and includes a discussion about empty binding:


The above code completes the binding.  Pretty simple right?  The nice thing about ObservableCollection is that it already implements notification events for us, and so there is no need to invoke INotifyPropertyChanged to notify the view that items have been added.

I ran the code, and the menu options did indeed show.  However, there were two things I noticed that I wanted to enhance:

-          The default font size was too small for my specific title screen

-          Selecting an item displayed a checkbox at right.  I wanted to remove this

At first I thought: easy enough, I can change the FontSize property of the control.  Well, it turned out not being this trivial.  Also, there was no property to just turn off checkboxes. 

After some digging, I read up on two parts of Windows 8 that seemed handy: styles and control templates.  Here are some references:


Control Templates:


One important note.  While you can easily just modify a portion of a control’s style, when dealing with templates, you must do more by essentially re-specifying the visual tree of the control.  In this blog, I take two approaches.  In one case, I rebuild the visual tree myself by just adding a few components.  In the other case, Visual Studio helps me out by allowing me to make a copy of the full (and lengthy!) control template for a control where I can then make the modifications I need.  Here’s the best part: templates and styles only modify aesthetics, not functionality, so you could literally redesign a button to be, say, round with a gradient fill.

Since I wanted to remove checkboxes, simply editing a style wouldn’t suffice; I needed to modify the control template of the ListView control.  Since I had to do this step, I wanted to do things in a fancy manner.  I thought to myself: If I need to modify a control template, perhaps I should also just redesign the control to be a grid with an ellipse and text sitting over it.  The ellipse would have a gradient fill, and on top of it centered would be the list of menu options contained in a ListBox instead of a ListView.  I chose the ListBox since it didn’t use checkboxes for selected items, which I wanted.


OK so you may be asking: “Dave, why didn’t you just use a ListBox instead of a ListView in the first place?”  Ah-ha!  To achieve what I wanted for my game, I had to modify something.  Let me demonstrate.  Take a simple Basic Page in XAML for Windows 8.  Let’s simply take the default black background, add a ListBox, add items to it, and try forcing the background to transparent since by default it appears to be white.  A snippet of the XAML code would look like this:


<ListBox HorizontalAlignment="Left" Height="392" Margin="276,166,0,0" Grid.Row="1" VerticalAlignment="Top" Width="603" Background="Transparent">

        <ListBoxItem Content="This is Item 1" FontSize="38"></ListBoxItem>

        <ListBoxItem Content="This is Item 2" FontSize="22"></ListBoxItem>

        <ListBoxItem Content="This is Item 3" FontSize="74"></ListBoxItem>


Figure 2: Simple XAML Code for a ListBox**


For me, the sample app for the basic page would look like this:



Figure 3: The App Running with a Simple ListBox (Screenshot take from Visual Studio 2012 Simulator)


Well then.  So, even though I tried forcing the background to transparent, clearly it stays as white.  This default is fine generally speaking, but I was particularly aiming for a dark control background on a dark application backdrop.  This is why I needed to modify the ListBox for my purpose.


At this point, let me take a moment to share with you more of my XAML code.  At first, I thought that simply making a ListBox style was all I needed to keep the background transparent.  Well, when running the app I found that the background was white or transparent depending on the control having focus or not.  Thus, I needed to tell the control not to have a white background when it didn’t have focus.  This required modifying the visual state specification of the ListBox.  This led me to modify the control template of the ListBox, and Visual Studio actually helped me out with this task; the IDE creates a copy of the control template for you!  I discuss this in detail below.  By the way, you don’t have to use Visual Studio do this.  Many actually prefer using Blend to edit templates.  Here is a good link showing how this could be done:

After Visual Studio helped me out, it filled out the ListBox style for me as ListBoxStyle1. Here is the full specification of my ListView with the custom control template specifying a tree structure of gridàellipseàlist box where Visual Studio populates the list box style:


<ListView x:Name="menu_list" Height="373" ItemsSource="{Binding}" FontFamily="Global User Interface" Foreground="White" Background="Black" Margin="-36,0,0,0" DataFetchSize="-3" HorizontalAlignment="Right" Width="504">

                <ListView.Template >

                    <ControlTemplate TargetType="ListView">


                            <Ellipse Width="300" Height="300" Margin="102,0" HorizontalAlignment="Center" VerticalAlignment="Center">


                                    <LinearGradientBrush StartPoint="0,0.5" EndPoint="1,0.5">

                                        <GradientStop Offset="0" Color="Gold"/>

                                        <GradientStop Offset=".5" Color="Black"/>




                            <Border Background="Transparent">

                                <ListBox HorizontalAlignment="Center" VerticalAlignment="Center" ItemsSource="{TemplateBinding ItemsSource}" FontSize="30" Style="{StaticResource ListBoxStyle1}"/>






Figure 4: The XAML Code for my ListView with ControlTemplate Modified**

As mentioned above, the items source binds to the current data context for the parent ListView.  For the ControlTemplate, I specify the TargetType as a ListView since….well, that’s the list control type I’m using.  As mentioned, I then specify a grid with an overlapping ellipse with an overlapping ListBox.  This specification is straightforward, but in case you need to reference the classes, here are some links:






I specifically chose a parent grid because it allows controls to overlap (like the text box over the ellipse).  Also, note that for the ListView, I’m specifying my own control template; it’s relatively short.  However, here is where it gets tricky.  While I wanted the ListView to have a custom visual tree, I wanted the ListBox template to have the same structure but with two soft modifications: a gradient brush for the text and a background that is always be transparent regardless of if the list box focus state.  Of course, since I wanted to do all of these changes, as I mentioned earlier, I just let Visual Studio help me modify the control template copy.  All you need to do is right click a control and Visual Studio gives you several options regarding the template. When I created a copy of the template, Visual Studio automatically specified my control’s style as shown above.

Here is the auto-generated template copy with my modifications commented and highlighted:



        <Style x:Key="ListBoxStyle1" TargetType="ListBox">

<!--            <Setter Property="Foreground" Value="{StaticResource ListBoxForegroundThemeBrush}"/> -->


            <Setter Property="Foreground">


                    <LinearGradientBrush StartPoint="0,0.5" EndPoint="1,0.5">

                        <GradientStop Offset="0" Color="White"/>

                        <GradientStop Offset=".5" Color="SlateBlue"/>





            <Setter Property="Background" Value="{StaticResource ListBoxBackgroundThemeBrush}"/>

            <Setter Property="BorderBrush" Value="{StaticResource ListBoxBorderThemeBrush}"/>

            <Setter Property="BorderThickness" Value="{StaticResource ListBoxBorderThemeThickness}"/>

            <Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Disabled"/>

            <Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto"/>

            <Setter Property="ScrollViewer.HorizontalScrollMode" Value="Disabled"/>

            <Setter Property="ScrollViewer.IsHorizontalRailEnabled" Value="True"/>

            <Setter Property="ScrollViewer.VerticalScrollMode" Value="Enabled"/>

            <Setter Property="ScrollViewer.IsVerticalRailEnabled" Value="True"/>

            <Setter Property="ScrollViewer.ZoomMode" Value="Disabled"/>

            <Setter Property="ScrollViewer.IsDeferredScrollingEnabled" Value="False"/>

            <Setter Property="ScrollViewer.BringIntoViewOnFocusChange" Value="True"/>

            <Setter Property="IsTabStop" Value="False"/>

            <Setter Property="TabNavigation" Value="Once"/>

            <Setter Property="FontFamily" Value="{StaticResource ContentControlThemeFontFamily}"/>

            <Setter Property="FontSize" Value="{StaticResource ControlContentThemeFontSize}"/>

            <Setter Property="ItemsPanel">







            <Setter Property="Template">


                    <ControlTemplate TargetType="ListBox">

                        <Border x:Name="LayoutRoot" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}">


                                <VisualStateGroup x:Name="CommonStates">

                                    <VisualState x:Name="Normal"/>

                                    <VisualState x:Name="Disabled">


                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="LayoutRoot">

                                                <DiscreteObjectKeyFrame KeyTime="0" Value="Transparent"/>


                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="BorderBrush" Storyboard.TargetName="LayoutRoot">

                                                <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource ListBoxDisabledForegroundThemeBrush}"/>





                                <VisualStateGroup x:Name="FocusStates">

                                    <VisualState x:Name="Focused">


                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="LayoutRoot">

  <!--                                              <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource ListBoxFocusBackgroundThemeBrush}"/> -->

                                                    <DiscreteObjectKeyFrame KeyTime="0" Value="Transparent"/>




                                    <VisualState x:Name="Unfocused">



                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="LayoutRoot">

                                                <DiscreteObjectKeyFrame KeyTime="0" Value="Transparent"/>








                            <ScrollViewer x:Name="ScrollViewer" BringIntoViewOnFocusChange="{TemplateBinding ScrollViewer.BringIntoViewOnFocusChange}" HorizontalScrollMode="{TemplateBinding ScrollViewer.HorizontalScrollMode}" HorizontalScrollBarVisibility="{TemplateBinding ScrollViewer.HorizontalScrollBarVisibility}" IsHorizontalRailEnabled="{TemplateBinding ScrollViewer.IsHorizontalRailEnabled}" IsVerticalRailEnabled="{TemplateBinding ScrollViewer.IsVerticalRailEnabled}" IsDeferredScrollingEnabled="{TemplateBinding ScrollViewer.IsDeferredScrollingEnabled}" Padding="{TemplateBinding Padding}" TabNavigation="{TemplateBinding TabNavigation}" VerticalScrollBarVisibility="{TemplateBinding ScrollViewer.VerticalScrollBarVisibility}" VerticalScrollMode="{TemplateBinding ScrollViewer.VerticalScrollMode}" ZoomMode="{TemplateBinding ScrollViewer.ZoomMode}">









Figure 5: A lot of ListBox Template Code!**

After creating a copy of the list control’s control template, I noticed that the auto-filled markup was pretty hefty!  Well, this is expected, since this is the complete visual tree specification of the control.  I surely didn’t want to manually write this whole visual tree markup myself so I definitely say thanks to Microsoft for creating this ability to make template copies.

Reading the code from top to bottom, the first set of highlighted markup uses a linear gradient brush (as I showed earlier) to make the list box text look fancy.  The second set of highlighted code changes the control’s background from white to transparent when it doesn’t have focus.  With all of this code I had written, so long as something was selected (control focused), I didn’t have the white background issue; it was only the case when I either clicked away from the control or when first running the app with the control out of focus.  By modifying this template, problem solved!  The best part: I didn’t have to memorize the verbose markup to modify the visual states of the control and the corresponding color properties.

By the way, here is a good read on visual states:

Here is the final polished product:




That’s it!  Thanks for reading!  Let me know if there are any questions, comments, ideas, etc.


**This sample source code includes XAML code automatically generated by Visual Studio IDE and is released under the Intel OBL Sample Source Code License (MS-LPL Compatible)


***This sample source code is released under the Microsoft Limited Public License (MS-LPL)


Para obtener información más completa sobre las optimizaciones del compilador, consulte nuestro Aviso de optimización.