Home > Articles > Programming > C#

This chapter is from the book

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

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

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 DEBUG
      if (System.Diagnostics.Debugger.IsAttached)
      {
        this.DebugSettings.EnableFrameRateCounter = true;
      }
#endif

      Frame rootFrame = Window.Current.Content as 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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020