Windows Phone 7 Quick Tutorials: Part 1 - Hello World

Developing applications for the Windows Phone 7 is possible either in Silverlight or XNA. This series of articles is about developing with Silverlight. In this article I will show how to write a simple, classic "Hello World" application.

Tools

Before you start writing applications for WP7 you'll need the WP7 Developer Tools. They are available to download for free here. The following will be installed:

  • Visual Studio 2010 Express for Windows Phone
  • Express Blend 4 for Windows Phone
  • Silverlight for Windows Phone 7
  • XNA Game Studio for Windows Phone 7
  • Windows Phone Emulator
  • Phone Registration Tool

Of course, if you already have VS 2010 the setup will only add the necessary support to developer for WP7 to your IDE.

Read more about the tools on Scott Guthrie's blog.

Note: Making the application available to the marketplace is another story and will not be discussed in this series.

Create a Simple Windows Phone Application

Having installed the WP7 Developer Tools you are ready to start writing WP7 applications. If you open Visual Studio 2010 you'll see several templates under the category "Silverlight for Windows Phone". The one we'll use in this article is the first one, simply called "Windows Phone Application". We'll call this first application WP7HelloWorld. This application will display a list of available languages and when selecting one language, the application will greet us with "hello world" in that language.

the application will greet us with

The wizard will create a project that looks like this:

wizard will create a project

There are two XAML files, one App.xaml for the Application class, and the other MainPage.xaml for the main page of your application. In addition there are several images including an application icon (though all of them are PNGs). If you open the MainPage.xaml you'll see an image of the page in the design pane.

open the MainPage.xaml you'll see an image of the page in the design pane

The XAML code of the page is listed below.

<phone:PhoneApplicationPage 
    x:Class="WP7HelloWorld.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"
    shell:SystemTray.IsVisible="True">

    <!--LayoutRoot is the root grid where all page content is placed-->
    <Grid x:Name="LayoutRoot" Background="Transparent">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <!--TitlePanel contains the name of the application and page title-->
        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
            <TextBlock x:Name="ApplicationTitle" Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}"/>
            <TextBlock x:Name="PageTitle" Text="page name" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
        </StackPanel>

        <!--ContentPanel - place additional content here-->
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"></Grid>
    </Grid>
 
    <!--Sample code showing usage of ApplicationBar-->
    <!--<phone:PhoneApplicationPage.ApplicationBar>
        <shell:ApplicationBar IsVisible="True" IsMenuEnabled="True">
            <shell:ApplicationBarIconButton IconUri="/Images/appbar_button1.png" Text="Button 1"/>
            <shell:ApplicationBarIconButton IconUri="/Images/appbar_button2.png" Text="Button 2"/>
            <shell:ApplicationBar.MenuItems>
                <shell:ApplicationBarMenuItem Text="MenuItem 1"/>
                <shell:ApplicationBarMenuItem Text="MenuItem 2"/>
            </shell:ApplicationBar.MenuItems>
        </shell:ApplicationBar>
    </phone:PhoneApplicationPage.ApplicationBar>-->

</phone:PhoneApplicationPage>

You can see the code is defining the following:

  • The root element is an PhoneApplicationPage control
  • The page content is placed into a grid, called by default LayoutRoot; this grid has two rows one for the title and one for the content
  • A stack panel with two text blocks, for the application and page title; these stack represents the title panel.
  • A grid, by default called ContentPanel, where you can place additional content
  • An ApplicationBar control, which is commented out by default

The content of the page can be customized to your needs, but this is the default the wizard creates for you.

Adding Content to the Main Page

The application will have the title "hello world" and the page title "greetings". The content area will be represented by a list whose items will be various languages. When the user will click on an item, the page title will display the text "hello world" in that language.

So the first step is to define a list. The XAML code of the MainPage will change to:

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
    <ListBox x:Name="LanguageList" 
                Grid.Row="0"
                SelectionChanged="LanguageList_SelectionChanged">
    </ListBox>
</Grid>

The translations for the "hello world" text are stored in a dictionary, whose key is the language (if I got the translations wrongs, it's Google Translator's fault). When the user selects a new item, handler LanguageList_SelectionChanged is called and the page title is updated.

public partial class MainPage : PhoneApplicationPage
{
    Dictionary<string, string> greetings;

    // Constructor
    public MainPage()
    {
        InitializeComponent();

        greetings = new Dictionary<string, string>();
        greetings["English"] = "Hello world";
        greetings["French"] = "Bonjour tout le monde";
        greetings["German"] = "Hallo Welt";
        greetings["Spanish"] = "Hola mundo";
        greetings["Portuguese"] = "OlC! mundo";
        greetings["Italian"] = "Ciao a tuti";
        greetings["Romanian"] = "Salutare lume";

        LanguageList.ItemsSource = greetings.Keys;
    }

    private void LanguageList_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        PageTitle.Text = greetings[LanguageList.SelectedItem as string];
    }
}


Related Articles

Windows Phone 7 Quick Tutorials: Part 1 - Hello World

Building and Deploying

You can now build and run the project. You can choose to deploy it either to the Windows Phone 7 Emulator (a virtual machine running the same operating system as the actual devices), installed with the Developer Tools, or into an actual device. You can select one of the two from the WP7 target combo.

[WP7_part1_4.png]

We'll consider the emulator for the time being.

After deployment, the application will automatically show up in the emulated phone. The image below show the application at startup and after the user selected Spanish in the list.

[WP7_part1_5.png]

Getting the App a Facelift

Let's customize the application a little bit: instead of showing a simple list of languages, the new list will show a flag next to each language, the flag of the country defining each language.

First step is to change the definition of the language by adding an ItemTemplate section, that looks like this.

<ListBox x:Name="LanguageList" 
            Grid.Row="0"
            SelectionChanged="LanguageList_SelectionChanged">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Margin="0,0,0,17" Orientation="Horizontal">
                <Image Source="{Binding Icon}" />
                <TextBlock Text="{Binding Language}" 
                              TextWrapping="Wrap" 
                              Margin="12,-6,12,0" 
                              Style="{StaticResource PhoneTextExtraLargeStyle}" />
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

(For more styles, such as PhoneTextExtraLargeStyle see Theme Resource for Windows Phone).

Second, we'll create an INotifyPropertyChanged implementation that will represent the items of the list box.

    public class LanguageItemViewModel : INotifyPropertyChanged
    {
        private string _Language;
        public string Language
        {
            get
            {
                return _Language;
            }
            set
            {
                if (value != _Language)
                {
                    _Language = value;
                    NotifyPropertyChanged("Language");
                }
            }
        }

        private BitmapImage _image;
        public BitmapImage Icon
        {
            get
            {
                return _image;
            }
            set
            {
                if (value != _image)
                {
                    _image = value;
                    NotifyPropertyChanged("Icon");
                }
            }
        }
        
        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged(String propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (null != handler)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }

Third, we'll have to change the item source for the list elements. It used to be the collection of keys in the dictionary, but now it will look like this:

LanguageList.ItemsSource = from g in greetings.Keys
                           select new LanguageItemViewModel
                           {
                               Icon = new BitmapImage(
                                          new Uri(String.Format("Images\\{0}.png", g), 
                                                  UriKind.Relative)),
                               Language = g
                           };

Fourth, then handler for the selection change must be updated, but the change is quite simple.

private void LanguageList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    LanguageItemViewModel item = LanguageList.SelectedItem as LanguageItemViewModel;
    if(item != null)
    {
        PageTitle.Text = greetings[item.Language];
    }
}

And last, we need images for the flags, stored under the Images folder in the project root (otherwise you have to change the Uri of the BitmapImages created in the constructor of the main page). After all these changes the project looks like this.

[WP7_part1_6.png]

Having made all these changes, the application will now look like in the following image (and of course the behavior will be the same).

[WP7_part1_7.png]

Conclusions

In this first article of the series we've seen how to create a simple "hello world" Silverlight application displaying this text in several languages. All you need for this is the Windows Phone 7 Developer Tools available for free to download, and some knowledge of Silverlight. In the next article we'll see how to use the pivot and the panorama control.



Related Articles



About the Author

Marius Bancila

Marius Bancila is a Microsoft MVP for VC++. He works as a software developer for a Norwegian-based company. He is mainly focused on building desktop applications with MFC and VC#. He keeps a blog at www.mariusbancila.ro/blog, focused on Windows programming. He is the co-founder of codexpert.ro, a community for Romanian C++/VC++ programmers.

Downloads

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • This paper introduces IBM Java on the IBM PowerLinux 7R2 server and describes IBM's implementation of the Java platform, which includes IBM's Java Virtual Machine and development toolkit.

  • The explosion in mobile devices and applications has generated a great deal of interest in APIs. Today's businesses are under increased pressure to make it easy to build apps, supply tools to help developers work more quickly, and deploy operational analytics so they can track users, developers, application performance, and more. Apigee Edge provides comprehensive API delivery tools and both operational and business-level analytics in an integrated platform. It is available as on-premise software or through …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds