Updating XAML and C# Code
With the tour of the package manifest complete, we are ready to fill our blank app with a little bit of content. Let’s look at the remaining files in our project and update them where necessary.
The Main Page User Interface
Every app consists of one or more windows with one or more pages. Our HelloRealWorld project, created from the Blank App template, is given a single window with a single page called MainPage. It defines what the user sees once your app has loaded and the splash screen has gone away. MainPage, like any page that would be used in a XAML app, is implemented across two files: MainPage.xaml contains the user interface, and MainPage.xaml.cs contains the logic, often called the code-behind. Listing 1.1 shows the initial contents of MainPage.xaml.
LISTING 1.1 MainPage.xaml—The Initial Markup for the Main Page
<
Page
x
:
Class
="HelloRealWorld.MainPage"
xmlns
="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns
:
x
="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns
:
local
="using:HelloRealWorld"
xmlns
:
d
="http://schemas.microsoft.com/expression/blend/2008"
xmlns
:
mc
="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc
:
Ignorable
="d">
<
Grid
Background
="{
ThemeResource
ApplicationPageBackgroundThemeBrush
}">
</
Grid
>
</
Page
>
At a quick glance, this file tells us:
- This is a class called MainPage (in the HelloRealWorld namespace) that derives from a class called Page (the root element in this file).
- It contains an empty Grid (an element examined in Chapter 4, “Layout”) whose background is set to a theme-defined color. From running the app, we know this color is a very dark gray (#1D1D1D).
- It contains a bunch of XML namespaces to make adding new elements and attributes that aren’t in the default namespace more convenient. These XML namespaces are discussed in the next chapter.
Listing 1.2 updates the blank-screen MainPage.xaml with a few elements to produce the result in Figure 1.8.
LISTING 1.2 MainPage.xaml—Updated Markup for the HelloRealWorld App
<
Page
x
:
Class
="HelloRealWorld.MainPage"
xmlns
="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns
:
x
="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns
:
local
="using:HelloRealWorld"
xmlns
:
d
="http://schemas.microsoft.com/expression/blend/2008"
xmlns
:
mc
="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc
:
Ignorable
="d">
<
Grid
Background
="{
ThemeResource
ApplicationPageBackgroundThemeBrush
}">
<
StackPanel
Name
="stackPanel"
Margin
="100"
Background
="Blue">
<
TextBlock
FontSize
="80"
TextWrapping
=
"WrapWholeWords"
Margin
="12,48">
Hello, English-speaking world!
</
TextBlock
>
<
TextBlock
FontSize
="28"
Margin
="12">Please enter your name:
</
TextBlock
>
<
Grid
>
<
Grid.ColumnDefinitions
>
<
ColumnDefinition
/>
<
ColumnDefinition
Width
="Auto"/>
</
Grid.ColumnDefinitions
>
<
TextBox
Name
="nameBox"
Margin
="12"/>
<
Button
Grid.Column
="1"
Click
="Button_Click">Go
</
Button
>
</
Grid
>
<
TextBlock
Name
="result"
FontSize
="28"
Margin
="12"/>
</
StackPanel
>
</
Grid
>
</
Page
>
FIGURE 1.8 The HelloRealWorld user interface asks the user to type his or her name.
This listing adds a bunch of new content inside the topmost Grid. The Grid and StackPanel elements help to arrange the user-visible elements: TextBlocks (i.e. labels), a TextBox, and a Button. All of these elements are described in depth in upcoming chapters.
The idea for this app is to display the user’s name in the TextBlock named result once he or she clicks the Go Button. (Granted, this is not a useful app, but it’s all we need to demonstrate the concepts throughout the remainder of this chapter.) To act upon the Button being clicked, this XAML specifies that a method called Button_Click should be called when its Click event is raised. This method must be defined in the code-behind file, which we’ll look at next.
The Main Page Logic
Listing 1.3 shows the initial contents of MainPage.xaml.cs, the code-behind file for MainPage.xaml. Until we add our own logic, it contains only a required call to InitializeComponent that constructs the page with all the visuals defined in the XAML file. The class is marked with the partial keyword because its definition is shared with a hidden C# file that gets generated when the XAML file is compiled.
LISTING 1.3 MainPage.xaml.cs—The Initial Code-Behind for the Main Page
using
System;using
System.Collections.Generic;using
System.IO;using
System.Linq;using
System.Runtime.InteropServices.WindowsRuntime;using
Windows.Foundation;using
Windows.Foundation.Collections;using
Windows.UI.Xaml;using
Windows.UI.Xaml.Controls;using
Windows.UI.Xaml.Controls.Primitives;using
Windows.UI.Xaml.Data;using
Windows.UI.Xaml.Input;using
Windows.UI.Xaml.Media;using
Windows.UI.Xaml.Navigation;// The Blank Page item template is documented at
// http://go.microsoft.com/fwlink/?LinkId=234238
namespace HelloRealWorld
{/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class
MainPage
:Page
{public MainPage()
{this.InitializeComponent();
} } }
We need to add an implementation of the Button_Click method referenced by the XAML. It can look as follows:
void
Button_Click(object
sender,RoutedEventArgs
e) {this
.result.Text =this
.nameBox.Text; }
The named elements in the XAML correspond to fields in this class, so this code updates the result TextBlock with the text from the nameBox TextBox. Figure 1.9 shows what this looks like, after the user types “Adam” then clicks the Button.
FIGURE 1.9 The result TextBlock contains the typed text after the user clicks the Button.
The Application Definition
The application definition is contained in App.xaml and its code-behind file, App.xaml.cs. App.xaml is a special XAML file that doesn’t define any visuals, but rather defines an App class that can handle application-level tasks. Usually the only reason to touch this XAML file is to place new application-wide resources, such as custom styles, inside its Application.Resources collection. Chapter 18, “Styles, Templates, and Visual States” contains many examples of this. Listing 1.4 shows the contents of App.xaml in our HelloRealWorld project.
LISTING 1.4 App.xaml—The Markup for the App Class
<
Application
x
:
Class
="HelloRealWorld.App"
xmlns
="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns
:
x
="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns
:
local
="using:HelloRealWorld">
</
Application
>
Listing 1.5 contains the auto-generated contents of the code-behind file for App.xaml. It contains three vital pieces:
- A constructor, which is effectively the app’s main method. The plumbing that makes it the app’s entry point is enabled by an “Entry point” setting in the package manifest (on the Application tab). When you create a project, Visual Studio automatically sets it to the namespace-qualified name of the project’s App class (HelloRealWorld.App in this example).
- Logic inside an OnLaunched method that enables the frame rate counter overlay in debug mode, navigates to the app’s first (and in this case only) page, and calls Window.Current.Activate to dismiss the splash screen. If you want to add a new page and make it be the starting point of the app, or if you want to customize the initialization logic, this is where you can do it. See Chapter 7, “App Lifecycle,” for more information.
- An OnSuspending method that is attached to the base class’s Suspending event. This gives you an opportunity to save state before your app is suspended, although the generated code does nothing here other than provide a TODO comment. Chapter 7 examines app suspension.
LISTING 1.5 App.xaml.cs—The Code-Behind for the App Class
using
System;using
System.Collections.Generic;using
System.IO;using
System.Linq;using
System.Runtime.InteropServices.WindowsRuntime;using
Windows.ApplicationModel;using
Windows.ApplicationModel.Activation;using
Windows.Foundation;using
Windows.Foundation.Collections;using
Windows.UI.Xaml;using
Windows.UI.Xaml.Controls;using
Windows.UI.Xaml.Controls.Primitives;using
Windows.UI.Xaml.Data;using
Windows.UI.Xaml.Input;using
Windows.UI.Xaml.Media;using
Windows.UI.Xaml.Navigation;namespace
HelloRealWorld {/// <summary>
///
Provides application-specific behavior to supplement the base class.
/// </summary>
sealed partial class
App : Application
{/// <summary>
///
Initializes the singleton application object. This is the first line
///
of authored code executed; the logical equivalent of main/WinMain.
/// </summary>
public
App() {this
.InitializeComponent();this
.Suspending += OnSuspending; }/// <summary>
///
Invoked when the application is launched normally by the end user.
///
Other entry points are used when the application is launched to open
///
a specific file, to display search results, and so forth.
/// </summary>
/// <param name="args">
Details about the launch request and process
.</param>
protected override void
OnLaunched(LaunchActivatedEventArgs
args) {#if
DEBUGif
(System.Diagnostics.Debugger
.IsAttached) {this
.DebugSettings.EnableFrameRateCounter =true
; }#endif
Frame
rootFrame =Window
.Current.Contentas
Frame;
// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active
if
(rootFrame ==null
) {// Create a Frame and navigate to the first page
var rootFrame
=new
Frame
();if
(args.PreviousExecutionState ==ApplicationExecutionState
.Terminated) {//TODO: Load state from previously suspended application
}// Place the frame in the current Window
Window.Current.Content = rootFrame;
}if
(rootFrame.Content ==null
) {// When the navigation stack isn't restored, navigate to the first page
if
(!rootFrame.Navigate(typeof
(MainPage
), args.Arguments)) {throw new
Exception
("Failed to create initial page"
); } }// Ensure the current Window is active
Window
.Current.Activate(); }/// <summary>
///
Invoked when application execution is being suspended. Application state
///
is saved without knowing whether the application will be terminated or
///
resumed with the contents of memory still intact.
/// </summary>
/// <param name="sender">
The source of the suspend request.
</param>
/// <param name="e">
Details about the suspend request.
</param>
private void
OnSuspending(object
sender,SuspendingEventArgs
e) {var
deferral = e.SuspendingOperation.GetDeferral();//TODO: Save application state and stop any background activity
deferral.Complete(); } } }
There’s one more file—AssemblyInfo.cs—but it’s not worth showing in this book. It contains a bunch of attributes where you can put a title, description, company name, copyright, and so on that get compiled into your assembly (the EXE or DLL). But setting these is unnecessary because all of the information used by the Windows Store is separately managed. Still, the AssemblyVersion and AssemblyFileVersion attributes, typically set to the same value, can be useful for you to keep track of distinct versions of your application:
[assembly
:AssemblyVersion
("1.0.0.0"
)] [assembly
:AssemblyFileVersion
("1.0.0.0"
)]
By using *-syntax, such as "1.0.*", you can even let the version number auto-increment every time you rebuild your app.