Writing your first Windows Phone 8 app (Part 3)

In Part 2 of this series, we talked about the basics of XAML and also designed the UI of our app with some basic XAML controls. In this part, we will make the app more functional by adding event handlers to these XAML controls.

As we can see from the image below, there are two buttons “Count” and “Reset” that need to be functional for the purpose of this app.

Counter App UI

  1. First, we go to the MainPage.xaml.cs, and declare a variable named “counter” of type integer and initialize it to 0.
    int counter = 0;
    
    // Constructor
    public MainPage()
    {
        InitializeComponent();
    }
  2. Open MainPage.xaml. Click on the Count button in the interface, and make sure you see the Name “CountButton” in the Properties panel in Visual Studio.Properties Panel
  3. Click on the Event Handler button (the highlighted button in the image above). Below, you will see a list of events that apply to the Button control.
    Go to the Tap event, and double-click on the text box next to it. You will see that it takes you to MainPage.xaml.cs and a method titled “CountButton_Tap” is automatically generated.

    int counter = 0;
    
    // Constructor
    public MainPage()
    {
        InitializeComponent();
    }
    
    private void CountButton_Tap(object sender, System.Windows.Input.GestureEventArgs e)
    {
    
    }
  4. Let’s complete the method. When the user taps on the Count button, we want the count displayed on the screen to be incremented.
    private void CountButton_Tap(object sender, System.Windows.Input.GestureEventArgs e)
    {
        counter++;
        CountText.Text = counter.ToString("N0");
    }

    (To understand the .ToString(“N0”), you can take a look at this.)

  5. Test the app in the emulator now. When you tap the Count button, the count on the screen should increase by 1.
  6. Next, we add an event to the Reset button just like we did for the Count button, and this is how our method looks like:
    private void ResetButton_Tap(object sender, System.Windows.Input.GestureEventArgs e)
    {
        counter = 0;
        CountText.Text = counter.ToString("N0");
    }

And we are done! When you tap the Count button, the count increases by 1, and when you tap the Reset button, it resets the count to 0. We have a completely functional app at this point, and this is great for a starter Windows Phone app.

You can download the source code of the app here.

One thought on “Writing your first Windows Phone 8 app (Part 3)

Leave a comment