The Application Class

,

XAML apps rely on an instance of the System.Windows.Application class to perform the startup activities of the app. Visual Studio’s Windows Phone App template creates an App class that subclasses the Application class. The App class consists of an App.xaml.cs file (the code-beside) containing a partial class and an accompanying App.xaml XAML file. The App.xaml file allows for resources, such as styles, to be defined in XAML and used throughout your app (see Listing 1.1).

The App class derives from the Application class by using the x:Class attribute in the Application element of the App.xaml file.

LISTING 1.1. App.xaml


<Application
    x:Class="HelloWorld.App"
    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">

    <!--Application Resources-->
    <Application.Resources>
<local:LocalizedStrings xmlns:local="clr-namespace:HelloWorld"
        x:Key="LocalizedStrings"/>
    </Application.Resources>

    <Application.ApplicationLifetimeObjects>
        <!--Required object that handles lifetime events for the application-->
        <shell:PhoneApplicationService
        Launching="Application_Launching" Closing="Application_Closing"
        Activated="Application_Activated"
        Deactivated="Application_Deactivated"/>
    </Application.ApplicationLifetimeObjects>

</Application>


Within App.xaml, the PhoneApplicationService is used to subscribe to application lifetime events. You look at lifetime events in greater detail in Chapter 3, “Understanding the Application Execution Model.”

Event handlers for lifetime events are located in the App class. You use this class to perform tasks before the UI is shown. The App class creates the PhoneApplicationFrame instance, which plays host to the MainPage, and any other pages, at runtime. The PhoneApplicationFrame is analogous to a web browser in that it handles navigation to and from each PhoneApplicationPage.

The App class also includes an event handler for unhandled exceptions. If an exception is raised anywhere in the app, from any thread, and it is not handled, the Application.UnhandledException event is raised, affording your app the opportunity to log the error or warn the user that an error has occurred.


Tip

If there are multiple Application classes within a project, the desired Application class can be specified by selecting the Startup Object in the project’s properties page. To open the properties page for a project, press Alt+Enter or right-click the project node in the Visual Studio Solution Explorer and select Properties.

Sometimes renaming a namespace can invalidate the Startup Object setting, which causes your app to silently fail during startup. If that happens, open the Properties tab and select a valid App class from the Startup Object drop-down list.


MainPage

The MainPage code-beside is shown in Listing 1.2. The using statement for Microsoft.Phone.Controls is particular to Windows Phone and contains controls such as the PhoneApplicationPage.

A commented region demonstrates how to initialize and populate the page’s ApplicationBar control. I ordinarily delete that code because I leverage a custom application bar wrapper that supports data-binding. You learn about the application bar in Chapter 8, “Taming the Application Bar.”


Tip

The using statements are placed in the code-beside file as a convenience, to save you time when writing code. It is a good practice to remove any unused using statements from a class because it decreases clutter and eliminates unnecessary dependencies, which can sometimes prevent compilation when linking class files across different projects, where the namespaces do not exist.


LISTING 1.2. MainPage.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using HelloWorld.Resources;

namespace HelloWorld
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();

            // Sample code to localize the ApplicationBar
            //BuildLocalizedApplicationBar();
        }

// Sample code for building a localized ApplicationBar
//private void BuildLocalizedApplicationBar()
//{
//    // Set the page's ApplicationBar to a new instance of ApplicationBar.
//    ApplicationBar = new ApplicationBar();

//    // Create a new button and set the text value to the localized string from AppResources.
//    ApplicationBarIconButton appBarButton = new ApplicationBarIconButton(new Uri("/Assets/AppBar/appbar.add.rest.png", UriKind.Relative));
//    appBarButton.Text = AppResources.AppBarButtonText;
//    ApplicationBar.Buttons.Add(appBarButton);

//    // Create a new menu item with the localized string from AppResources.
//    ApplicationBarMenuItem appBarMenuItem = new ApplicationBarMenuItem(AppResources.AppBarMenuItemText);
//    ApplicationBar.MenuItems.Add(appBarMenuItem);
//}
    }
}


MainPage.xaml contains the initial layout, with a Grid as the root content, a child StackPanel containing the application title and page title, and another Grid to place the page’s content (see Listing 1.3).

LISTING 1.3. MainPage.xaml


<phone:PhoneApplicationPage
    x:Class="HelloWorldXaml.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"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
    shell:SystemTray.IsVisible="True">

    <!--LayoutRoot contains the root grid where all other 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="24,24,0,12">
            <TextBlock x:Name="ApplicationTitle"
                   Text="MY APPLICATION"
                   Style="{StaticResource PhoneTextNormalStyle}"/>
            <TextBlock x:Name="PageTitle" Text="page name" Margin="-3,-8,0,0"
                   Style="{StaticResource PhoneTextTitle1Style}"/>
        </StackPanel>

        <!--ContentPanel - place additional content here-->
        <Grid x:Name="ContentGrid" Grid.Row="1">
        </Grid>
    </Grid>

</phone:PhoneApplicationPage>


The x:Class attribute indicates the code-beside type, which in this case is the HelloWorldXaml.MainPage class.

The mc:Ignorable="d" attribute is used to instruct the compiler to ignore any elements or attributes that begin with d:. The two attributes d:DesignHeight and d:DesignWidth are used at design time by Visual Studio and Expression Blend to render the page using the specified dimensions. These attributes are for your benefit and do not influence the page at runtime.

Various text related properties are set in the phone:PhoneApplicationPage element, specifically the FontFamily, FontSize, and Foreground properties. These indicate the default appearance of text in an element such as a TextBlock, when not specified on the element itself. This is an example of parent-child property value inheritance, where the child control uses the closest ancestor’s property value if it does not define its own.

Styles are set to predefined StaticResources, and colors vary according to what theme the user selected for the phone device, either light or dark and the selected accent color. For a complete list of predefined styles see http://bit.ly/cUmhGi.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.216.190.41