Tuesday, 7 August 2012

Build a Windows Phone 7 Clock App

19:23 Posted by: Sohel Parvez 0 comments

In this tutorial I will show you how to create a cool looking clock app for Windows Phone 7. Expression Blend will be used for designing this app as it is a very powerful tool for quickly creating compelling animations.

For following the tutorial you will need to download and install the Windows Phone 7 SDK. After finishing the installation you will end up with Visual Studio Express for Windows Phone 7, Expression Blend for Windows Phone 7, and Windows Phone Emulator.
The first step is to download and install the Windows Phone 7.5 SDK.
Before we start, here is the final image of what we are going to build.

Final App
The app itself is a very simple clock app that shows the time & date. We will use animation to bring in the elements when the application starts. The bulk of the work will be putting together the screen elements and aligning them properly and creating the startup animation. We will also add a little bit of code to update the date and time periodically.

Project Setup

First, you will need to create a project in Expression Blend. For this, you will need to select File > New Project in Expression Blend and select the Windows Phone Application Project template.
Provide a name for your project. I will use MinimalClock for my project.
Creating New Project
Once the project is created, select Project > Run Project to run your project. You will notice that the project compiles and then Blend launches the Windows Phone 7 emulator. Sooner or later, you will see your app running in the emulator. Hit the home button on the emulator to quit your app. Doing so will stop the debugging session and will get you to the home screen on your emulator. Once you’re done looking around in the emulator, switch back to Expression Blend.

Designing the UI

Now we will put together the UI for the MinimalClock app. After the project is created you will see this in your Expression Blend:
New Project in Expression Blend
First, we need to remove all the controls that were created by the project template for us. In the Objects and Timeline, right click on the TitlePanel and choose Delete to remove the control.
We also need to change the layout type to Canvas instead of Grid, so we can freely move around our controls. To do this, right-click on the ContentPanel and select Canvas in Change Layout Type menu.
Once finished, your Objects and Timeline should look like this.
Objects and Timeline
And your application page should be empty like this:
alt="Empty Application Page"
title="Empty Application Page" />
Now, we have the empty application page and we are ready to start adding controls to it.
On the toolbar menu, select the Text tool and TextBlock. Draw a rectangle on your application page in any size. We will fix the size later.
TextBlock tool
This will be the TextBlock that we will be using for displaying the hour part of the time, so we will need to rename it to TimeHour. We will also need to change this to be slightly larger.
TextBlock selected on Application page
On the right hand side, find the properties Window. Make sure that the TextBlock you have just created is selected and change its name to TimeHour and hit Enter.
Renaming TextBlock to TimeHours
Next, you will need to change the content of the TimeHour control, so navigate to the Text property and change its value to 12. Then hit Enter. A faster way to find any property on the properties tab is to use the search area and start typing the name of the property. Be careful to clear the search box after you have finished modifying your property as all the other properties will remain hidden by your search.
Changing the Text property of TimeHours to 12
Next, we will create a style for our TimeHour control. Styles are a collection of visual properties that can be applied on a given control type. We will be saving a lot of work with styles. This can be done by right clicking on the control itself in the Objects and Timeline palette and navigate to the Edit Style menu and select Create Empty
Creating an Empty Style
Next, we need to give the name of the style: TimeTextStyle, and then make sure to select This Document where the style will be defined.
Creating Style Resource
After creating the style, we will find ourselves in the style editor. You will be recognizing it by looking at the editor Window
Style editor for TimeTextStyle
On the properties pane, change the following. Do a search for Font in the Property Search field, but do not forget to clear it later to unhide the other properties.
  • Font: Segoe WP
  • Font: Size: 164
  • Font Wight: Bold
Style changes for TimeTextStyle
You will also need to change the Height and Width to Auto in our style, by clicking on the small crossed arrow symbol right next to the size field.
Setting Height and Width to Auto
Now we are done editing our style, so we can leave the style edit mode clicking on the TimeHours label on the top of our design surface.
Finishing editing our style
Now, we need another TextBlock to show the minutes for the current time and another for showing the dots between them. For this, select the TimeHours on the Objects and Timeline and press Ctrl-C to copy and press Ctrl-V twice to create two copies. You wil end up with this in your Objects and Timeline panel.
Duplicating the TimeHours control
You will need to do the following changes:
  • Rename TimeHours_Copy to TimeDots
  • Change the Text property to :
  • Rename TimeHours_Copy1 to TimeMinutes
  • Change TimeMinutes Text property to 59

Positioning the Time Elements

Now, we have all the textblocks that we need for displaying the Time. All we need is to align them and place them a bit further away from each other.
First, you will need to select all three controls in the Objects and Timeline palette and right-click on them, select Align and Vertical Centers.
Aligning textblocks
You will need to put a littlebit of spacing between the time elements. For moving the elements precisely, you can use the arrow keys. If you use the arrow keys the control will move one pixel in the given directions and if you use the arrow with shift key then the control will be moved by 10 pixels.
Select the TimeHours textblock on the Ojects and Timeline palette and move it 5 pixels left. Select the TimeMinutes textblock and press the right arrow five times to move it right 5 pixels. Once, you are done you will end up with omething like this.
Nudging textblocks
Finally, we will need to combine the elements into a single control, so it will be easier to manipulate later.
To do this you will need to select all TimeHours, TimeDots and TimeMinutes on the Objects and Timeline palette. Right click on the selected items and choose Group Into and Canvas.
Combining textblocks
Double click on the newly created [Canvas] element and rename it to TimeText. Now your object structure should look like this.
TimeText textblock

Adding Bars and the application title

Lastly, we will add two bars. One vertical and one horizontal to make the UI a bit more interesting. We will also add the name of the app.
First, make sure that ContentPanel is selected on the Objects and Timeline palette, then select the Rectangle on the toolbar or use its shortcode M. Draw a horizontal rectangle just above the TimeText control. Next, you will need to change the properties of this rectangle. Make sure that your rectangle is selected and on the Properties palette change the following:
  • Set Name property to HorizontalSeparator.
  • Set Height property to 4 px.
  • Set Width property to 587 px.
Now we are going to change the fill property of the HorizontalSpearator to one of the built in styles called PhoneAccentBrush. This will reuse the current selected theme’s accent color. With this modification the application will reuse the primary color of the current theme.
In order to change the fill, select HorizontalSeparator and locate the last tab on the color editor called Brush resources. Then select the PhoneAccentBrush from the list.
Selecting the PhoneAccentBrush
Also, we need to set the Stroke property of HorizontalSeparator to No Brush. You can do this by selecting Stroke property just right under of the Brush property and then select the first tab on the color editor.
Changing the Fill property to No Brush
We need a second bar called horizontal bar. For this, once more select the Rectangle tool or hit M to select it. Draw a rectangle just below the TimeText control and set the following properties.
  • Set the Name property to VerticalSeparator
  • Fill to PhoneAccentBrush
  • Stroke to No Brush
  • Width to 4px
  • Height to 350px
These separators will go over the boundaries of the screen, but this is intended. You will need to position the separators around the Time part like this:
Separators are placed around time
Now we need to add the application title. Select the TextBlock tool from the Tools palette or press T. Draw a TextBlock just above the HorizontalSeparator and change the following properties.
  • Set the Name property to ApplicationTitle
  • Set the Text property to MOBILETUTS MINIMAL CLOCK
  • Set the Foreground property to PhoneAccentStyle
  • Set the FontSize property to 12pt
This is what it should look like now:
Application title positioned

Creating Seconds

To create the seconds you will need to add a new TextBlock to the application page. Select the TextBlock tool from the Tools palette, or press the T key.
TextBlock tool
Draw a TextBlock just below the Time and set the following properties:
  • Set the Name property to SecondsLabel
  • Set the Text property to seconds.
Next we will define a style for this element and later we will reuse this style for formatting the day labels as well.
To create a new style select the SecondsLabel on the design surface, right click on it and in the Edit Style menu, choose Create Empty.
Creating the SmallTextStyle
Give SmallTextStyle as the name of style and click on the OK button to create the style.
Created the SmallTextStyle
Next, you will find yourself in the style editor. Change the following property:
  • Set the Font Size to 28px.
Also, set the top and bottom margin to 2 pixels.
Setting the margins
You can leave the style editing mode by clicking on the SecondsLabel on the top-left area on your design surface.
Leaving style editing
Draw a second TextBlock below SecondsLabel and change the properties like this:
  • Set the Name property to TimeSeconds
  • Set the Text property to 59
  • Set the FontSize property to 140pt
  • Set the Width property to 210px
With all the changes the phone application page should look like this:
Application page with seconds added

Creating Date

Now we are ready to create the part that will display the current date. For this select again the TextBlock tool or press the T key to access it quickly.
Draw a TextBlock just right above the HorizontalSeparator control and change its properties as the following:
  • Set the Name property to DateText
  • Set the Text property to 2012/12/13
  • Set the Font Size to 22 pt.
Here is how the application page looks after adding the DateText.
Date added to application page

Creating Days

Finally, we will create the control responsible for displaying the days. We will need seven TextBlock to display each day of the week. You will need to add the m one by one. Select the TextBlock tool from Tool palette or press the T key and place all TextBlocks on the right side of the VerticalSeparator.
  • Monday
    • Set the Name property to Day1
    • Set the Text property to mon
  • Tuesday
    • Set the Name property to Day2
    • Set the Text property to tue
  • Wednesday
    • Set the Name property to Day3
    • Set the Text property to wed
  • Thursday
    • Set the Name property to Day4
    • Set the Text property to thu
  • Friday
    • Set the Name property to Day5
    • Set the Text property to Fri
  • Saturday
    • Set the Name property to Day6
    • Set the Text property to sat
  • Sunday
    • Set the Name property to Day7
    • Set the Text property to sun
For each of the day text block change the style by right clicking one the controls one by one, select the Edit Style menu and then choose the Apply Resource. Select style SmallTextStyle that we defined earlier.
alt="Selecting SmallTextStyle" title="Selecting SmallTextStyle" />
After this we need to arrange the textblocks as shown in the screenshot below.
Ordering the days
If the days not aligned correctly, then select them all in the Objects and Timeline palette, right click and select Left Edges from Align menu.
Next we need to combine the days into a new container, so we can manipulate them easier later. With all the days selected, right click on them and select StackPanel from the Group Into menu.
Combining days to StackPanel
Double click on the newlz created [StackPanel] element and change it’s name to WeekDays.
We have one last step in order to finish the UI design phase and to get to the planned look of our application. We need to slightly rotate our whole UI.
For this, select the ContentPanel in the Objects and Timeline palette and then go to the Properties and change and in the Transform property group, change the Rotation Angle to -30 degrees.
Rotating the ContentPanel
After looking at the rotated screen, we notice that the screen elements are slightly off. They need to be repositioned in order to look nicer when rotated.
Rotated screen
We need to change the position of the DateText and the ApplicationTitle. You will need to change the following properties:
  • Set the Left property of DateText to 380.
  • Set the Width property of HorizontalSeparator to 620, so it goes over the screen boundaries.
  • Set the Left property of the ApplicationTitle to 16 to bring the application title to closer to the center of the screen.
You can also select the control that you would like to reposition and use the arrow keys for slightly moving around the controls pixel by pixel and use Shift key with the Arrow keys to move them around 10 pixels at a time.
Now that all the controls are in place, the UI is done and the animations can be added.
Final Application Page
### Device Tab
In the initial screenshot you can see that the separator lines are red, but in my screenshot they are blue. This happens, because the device has different accent color set up. You can change the device theme, by clicking the Device tab just next to the Project tab. Here you will be able to change the orientation of the device, applying different accent color and see how the application look like if the dark or light theme is selected. I encourage you to play around a little with the settings.
Device tab

States and Storyboards

Next, we will create the initial animation that will be playing when the application launched. The animation will move the TimeText, WeekDays, TimeSeconds, DateText controls to their initial location.
Animations in Expression Blend are based on creating key frames and then modify certain properties in that key frame. This will tell the animation subsystem that the property needs to be animated and the value should be as specified in the key frame. For example, if you create a key frame at 1 seconds for the TimeText and then change the location of and opacity of the control then these properties will be animated.

Creating Storyboard for the initial animation

First, you need to create a new story board in the Objects and Timeline palette by pressing the + button.
New storyboard
Provide the name InitialAnimation for your new storyboard and click Ok to create it.
Creating new storyboard
Now that we have the storyboard created, you will see something like this in the Objects and Timeline palette. On the left hand side you will see that our storyboard called InitialAnimation is selected and the little red led indicates that the recording is on. This means that if we change any properties of any control it will be part of the storyboard instead of changing the UI.
Objects and Timeline

Animating TimeText Opacity

On the left hand side of the palette you can see the timeline part. Here you can move forward or backwards in time and you can add keyframes. Next, we will animate the TimeText and its Opacity property. We will animate the Opacity property from 0 percent to 100 percent in 1 second. In order to do this, select TimeText in the Objects and Timeline palette and make sure that the playhead is at 0 seconds and click the Record Keyframe button.
Record Keyframe
The result will be that a new keyframe is added for Timetext at 0 seconds. You will also notice that a little red dot is added to TimeText, this means that the InitialAnimation is changing this control.
0s TimeText keyframe
Now, you will need to go to the Properties palette and change the Opacity of TimeText to be 0 percent.
0s TimeText Opacity 0
Next, you will need to move the playhead to 1 second and click the Record Keyframe.
Record Keyframe
1s TimeText keyframe
Then again, go to the Properties palette and change the Opacity of TimeText to 100 percent.
1s TimeText Opacity 100
The animation is now ready and you can observe it by clicking the Play button:
Play Animation
You can move around the keyframes, if you want to tweak the animation.

Animating TimeText position

Select the 0 second keyframe from TimeText. Temporarily change back the Opacity property to 95 percent, so you can see what you are doing. Then a couple of times hit the Shift and Left Arrow key combination. With this, you will move out TimeText from the screen. This will be the starting position of our movement. Do not forget to change back the Opacity property to 0 percent.
Select the 1 seconds keyframe of TimeText then you will need to do the following. Hit once the right arrow key on your keyboard – moving the control 1 pixel to the right – and then hit the left arrow key once – moving the control 1 pixel to the left. With this change we will essentially record the current position of our TimeText control and instruct the storyboard to move it to this location regardless of the initial position.
Try to play the animation. If everything worked out, then you should see the TimeText moving in to the screen and gradually appearing at the same time.
One more thing we can do to spice up the animation is to configure the easing for the animation. This will make the animation more natural. For this, select the 1s key frame of our animation. Then change the Easing Function property to Back InOut on the Property palette.
Changing the Easing
Play the animation once again to show how the animation behaves now. If you would like, change the easing to see how each easing function behaves.

Animating TimeSeconds

Next, we will be animating TimeSeconds, the control used to display the seconds part of the current time. For this, select TimeSeconds and add keyframes to the timeline at 0 seconds and at 1 seconds. Then do the following:
  • Select the first key frame of TimeSeconds
  • Set the Opacity property of TimeSeconds to 0 percent.
  • Press the shift + down arrow keys together on your keyboard a couple of times to move TimeSeconds out of the screen.
  • Select the second key frame of TimeSeconds
  • Set the Opacity property of TimeSeconds to 100 percent.
  • Press the down arrow on your keyboard once and then the up arrow once to record the position of TimeSeconds.
  • Select the second keyframe and change the easing function to Back InOut.
Lastly, we will need to animate the controls that are responsible for displaying the current date and days in the application. These animation will be simple they will animate the opacity of these controls from 0 percent to 100 percent.
  • Select Weekdays in the Objects and Timeline palette and add a keyframe at 0 seconds.
  • Change the opacity to 0 percent
  • Move the playhead to 1 second
  • Add the second key frame by clicking on the Record keyframe button Record Keyframe.
  • Change the opacity to 100 percent.
  • Select the DateText control in the Objects and Timeline palette and add a keyframe at 0 seconds.
  • Change the opacity to 0 percent
  • Move the playhead to 1 second
  • Add the second key frame by clicking on the Record keyframe button Record Keyframe.
  • Change the opacity to 100 percent.

Setting up the initial state

One last thing needed to be done is to quit the animation mode and change the opacity to 0 for all controls that we are animating in the InitialAnimation story board. Close the storyboard in the Objects and Timeline palette by clicking the X button next to the story board name.
Close storyboard
Then select each of the controls animated and set their opacity properties to 0 percent.
Now that the animation is done, all is needed to add a bit of code to do the screen updating, so the content of our screen is updated each seconds and to start our initial animation when the application screen is loaded.

Writing a Little Code

Now the application is almost finished. All we need to do is to add a little bit of code to refresh the screen every half second and to play our initial animation.
In order to update the screen periodically, a DispatchTimer needs to be created when the page finishes loading. For this, an event handler for the page loaded event needs to be created.

Create Event Handlers

First, select the application page from the Objects and Timeline palette.
Select application page
Then on the Properties palette select the Events tab.
Select Events
In the list of events, select the Loaded event and double-click to create the event handler. A new window with the code behind for our application page.
Code view


First, the dispatch timer needs to be defined in the class file (MainPage.xaml.cs). A “using” statement needs to be added just after the last using stement at the top of the class file.
using System.Windows.Threading;
Then add the following line just after the class definition:
        private DispatcherTimer _timer;
In the Loaded event add the following code lines:

        RefreshUI(this, null);

        Storyboard sb = (Storyboard)this.Resources["IntialAnimation"];
        sb.BeginTime = TimeSpan.FromSeconds(0.1);

        _timer = new DispatcherTimer();
        _timer.Interval = TimeSpan.FromSeconds(0.4);
        _timer.Tick += RefreshUI;

What this piece of code will do is first call a method that will update the UI to the current time and day before the initial animation is set up to run in 0.4 seconds and will wire up our timer to run every half seconds and call the RefreshUI method.
Next, a new method needs to be added to stop the timer when we leave the application. The method called OnNavigatedFrom looks like this:

    protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)

        if (_timer != null)

One last piece is missing: the RefreshUI method that updates the UI.

    public void RefreshUI(object sender, EventArgs e)
        DateTime dt = DateTime.Now;

        int seconds = dt.Second;
        int minutes = dt.Minute;
        int hour = dt.Hour;

        int year = dt.Year;

        // Time 
        if (TimeHours.Text != dt.Hour.ToString())
            TimeHours.Text = dt.Hour.ToString();

        if (TimeMinutes.Text != dt.Minute.ToString("D2"))
            TimeMinutes.Text = dt.Minute.ToString("D2");

        if (TimeSeconds.Text != dt.Second.ToString("D2"))
            TimeSeconds.Text = dt.Second.ToString("D2");

The final code will look like this:
Final Code
If all went well, then after pressing Ctrl-Shift-B or select menu, Project, Build Project, the project should build without errors. If the project is built without any problem then select Project, Run Project to run the application.


This article just scratched the surface of what is possible using Blend for creating Windows Phone 7 apps. I would encourage you to take this app and experiment with animating the UI or alter the app in other ways. It is fun!


Post a Comment


2012 Learn How to do Organic SEO. All rights reserved. How to do Organic SEO