Home > Articles > Mobile Application Development & Programming

  • Print
  • + Share This
This chapter is from the book

Adding Code

This first Windows Phone application is not going to do much, but we should get started and make something happen with the phone. Because this is your first Windows Phone application, let’s not pretend it is a desktop application but instead show off some of the touch capabilities.

First, if you look at the text of the XAML you should see that the first line of text shows the root element of the XAML to be a PhoneApplicationPage. This is the basic class from which each page you create will derive. The x:Class declaration is the name of the class that represents the class. If you open the code file, you will see this code was created for you:

<phone:PhoneApplicationPage x:Class="HelloWorldPhone.MainPage"
  ...

You will need to open the code file for the XAML file. You can do this by right-clicking the XAML page and picking View Code, or you can simply press F7 to open the code file. The initial code file is pretty simple, but you should see what the basics are. The namespace and class name match the x:Class definition we see in the XAML. This is how the two files are related to each other. If you change one, you will need to change the other. You should also note that the base class for the MainPage class is the same as the root element of the XAML. They are all related to each other. Here is the initial code file:

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 HelloWorldPhone.Resources;

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

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

These two files (the .xaml and the code files) are closely tied to each other. In fact, you can see that if you find an element in the XAML that has a name, it will be available in the code file. If you switch back to the .xaml file, click the TextBlock that you created in Blend. You will notice in the Properties window that it does not have a name (as shown in Figure 2.24).

Figure 2.24

FIGURE 2.24. Naming an element in the Properties window

If you click the text “<no name>”, you can enter a name. Name the TextBlock “theStatus.” If you then switch over to the code file, you will be able to use that name as a member of the class:

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

    theStatus.Text = "Hello from Code";
  }
}
...

At this point, if you run the application (pressing F5 will do this), you will see that this line of code is being executed as the theStatus TextBlock is changed to show the new text (as seen in Figure 2.25).

Figure 2.25

FIGURE 2.25. Running the application

There is an important fact you should derive from knowing that named elements in the XAML become part of the class: The job of the XAML is to build an object graph. The hierarchy of the XAML is just about creating the hierarchy of objects. At runtime, you can modify these objects in whatever way you want.

When you stop your application, the emulator will continue to run. You can leave the emulator running across multiple invocations of your application. You should not close the emulator after debugging your application.

Working with Events

Because you are building a phone application, let’s show how basic events work. You can wire up events just as easily using standard language (for example, C#) semantics.2 For example, you could handle the Tap event on theStatus to run code when the text is tapped:

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

    theStatus.Text = "Hello from Code";

    theStatus.Tap += theStatus_Tap;

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

  void theStatus_Tap(object sender,
                     System.Windows.Input.GestureEventArgs e)
  {
    theStatus.Text = "Status was Tapped";
  }
}
...

When you tap on theStatus the Tap event will be fired (which is what causes the code in the event handler to be called). All events work in this simple fashion, but the number and type of events in Silverlight for Windows Phone vary widely.

Debugging in the Emulator

If clicking the user interface was not working the way we would like, it might help if we could stop the operation during an event to see what was happening during execution. We can do this by debugging our operation. We can use the debugger to set breakpoints and break in code while using the emulator. Place the text cursor inside the event handler and press F9 to create a breakpoint. When you run the application (again, press F5), you can see that when you click the theStatus TextBlock the debugger stops inside the event handler. You can hover your mouse over specific code elements (for example, theStatus.Text) to see the value in a pop-up (as shown in Figure 2.26).

Figure 2.26

FIGURE 2.26. Using the Visual Studio debugger

Pressing the F5 key while stopped at a breakpoint will cause the application to continue running. There are other ways to walk through the code, but for now that should be sufficient to get you started. Using the emulator is the most common way you will develop your applications, but there are some interactions that are difficult to do with the emulator (for example, multitouch, using phone sensors, and so on) for which debugging directly on a device would be very useful. Luckily, debugging on the device is supported and works pretty easily.

Debugging with a Device

If you have a phone with which you want to do your development, you will need to be able to deploy and debug directly on the phone itself. First, you need to connect your phone to your development machine. All you need to do is connect your phone to your computer by a USB cable.

‘Now that your device is connected, you can use it to browse to the directories for music, photos, and so on. However, before you can use a phone as a development device, you will need to register the phone for development. This lifts the requirements that applications be signed by Microsoft and allows you to deploy your applications directly to the phone so that you can debug applications.

Before you can enable your phone as a developer phone, you will need to have an account at the Windows Phone App Hub (http://developer.windowsphone.com). After you have done that, you can enable your phone to be used for development. To do this you will need the Windows Phone Developer Registration tool, which is installed when you install the Windows Phone SDK. When you run this application, it detects the device. You will need to ensure that the device is unlocked and turned on. At that point the Windows Phone Developer Registration tool will enable the Register button, as shown in Figure 2.27.

Figure 2.27

FIGURE 2.27. Windows Phone Developer Registration tool

Next, it will ask you for your Windows Live ID that you used to register with the developer portal, as shown in Figure 2.28.

Figure 2.28

FIGURE 2.28. Signing in with your Microsoft ID

If your phone is successfully attached to your computer, the Status area will tell you that it is ready to register your device for development. At this point, just click the Register button to register with the developer portal. After it registers the phone, it changes the status to show you that the phone is ready.

When you use a device to debug, you will find it much easier to change the default time-out of the device to be longer than the default (usually one minute, but it depends on the device manufacturer and carrier). To do this, go to the settings on your phone. In the settings is an option called “lock screen”, as shown in Figure 2.29.

Figure 2.29

FIGURE 2.29. The Lock Screen option on the settings screen

When you’re in this option, you can scroll down to find the “Screen times out after” option, open the option, and select the longest time-out you can tolerate (this will affect battery life when you’re not debugging on the device, so be careful to choose a time-out you can live with if it’s not a testing-only device). You can see this in Figure 2.30.

Figure 2.30

FIGURE 2.30. Changing the default device time-out

Now that you’ve registered your device, you can deploy and debug your applications using Visual Studio. The key to using the device instead of the emulator is to change the deployment using the drop-down list of deployment options. The drop-down is located in the toolbar of Visual Studio, as shown in Figure 2.31.

Figure 2.31

FIGURE 2.31. Changing the deployment to use a development phone

After you change the deployment target, you can debug just like you did with the emulator. When you run the application, it will deploy your application to the device and run it so that you can debug it in the same way as you did with the emulator.

Using Touch

Even though the touch interactions do fire mouse events, other events enable you to design your application for touch. Because touch is so important to how applications on the phone work, this first application should give you a taste of that experience. To show touch working, let’s add an ellipse to the application that the user can move around by dragging it with her finger. To get started, you should open the MainPage.xaml file and add a new ellipse in the center of the page. To do this, find the TextBlock called theStatus and place a new Ellipse element after it, like so:

...
    <Grid x:Name="ContentGrid"
          Grid.Row="1">
      <Rectangle Fill="#FF7E0505"
                 Margin="8"
                 RadiusY="24"
                 RadiusX="24" />
      <TextBlock HorizontalAlignment="Center"
                 TextWrapping="Wrap"
                 Text="Status"
                 VerticalAlignment="Bottom"
                 FontSize="48"
                 FontWeight="Bold"
                 Name="theStatus" />
      <Ellipse x:Name="theEllipse"
               Fill="White"
               Width="200"
               Height="200">
      </Ellipse>
    </Grid>
...

We need to be able to move the ellipse (named theEllipse) as the user drags it. To allow us to do this, we must use something called a transform. In XAML, a transform is used to change the way an object is rendered without having to change properties of the ellipse. Although we could change the margins and/or alignments to move it around the screen, using a transform is much simpler. You should use a TranslateTransform to allow this movement. A TranslateTransform provides X and Y properties, which specify where to draw the element (as a delta between where it originally exists and where you want it). You can specify this transform by setting the RenderTransform property with a TranslateTransform (naming it in the process):

...
<Ellipse x:Name="theEllipse"
         Fill="White"
         Width="200"
         Height="200">
  <Ellipse.RenderTransform>
    <TranslateTransform x:Name="theMover" />
  </Ellipse.RenderTransform>
</Ellipse>
...

Now that we have a way to move our ellipse around the page, let’s look at dealing with touch. In Silverlight, there are two specific types of touch interactions that are meant to allow the user to change onscreen objects. These are when the user drags her finger on the screen and when she uses a pinch move to resize objects. These types of interactions are called manipulations. Silverlight has three events to allow you to use this touch information:

  • ManipulationStarted
  • ManipulationDelta
  • ManipulationCompleted

These events let you get information about the manipulation as it happens. For example, let’s handle the ManipulationDelta event to get information about when the user drags on the screen. This event is called as the manipulation happens, and it includes information about the difference between the start of the manipulation and the current state (for example, how far the user has dragged her finger):

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

    theStatus.Text = "Hello from Code";

    theStatus.Tap += theStatus_Tap;

    theEllipse.ManipulationDelta += theEllipse_ManipulationDelta;

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

  void theEllipse_ManipulationDelta(object sender,
                                    System.Windows.Input.
                                    ManipulationDeltaEventArgs e)
  {
    // As a manipulation is executed (drag or resize), this is called
    theMover.X = e.CumulativeManipulation.Translation.X;
    theMover.Y = e.CumulativeManipulation.Translation.Y;
  }

  ...
}
...

The event is fired while the user either pinches or drags within the theEllipse element. In this case the code is only concerned with the dragging. In the event handler for ManipulationDelta, the ManipulationDeltaEventArgs object contains information about the extent of the manipulation. The CumulativeManipulation property of the event args has a property called Translation, which contains the extent of the drag operation (the complete delta). We are just changing theMover’s properties to match the manipulation. This means we can now drag the theEllipse element around and see it change position under our dragging, as shown in Figure 2.32.

Figure 2.32

FIGURE 2.32. Dragging the ellipse

  • + Share This
  • 🔖 Save To Your Account

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