Hello World from XAML and C++ /CX

We have previously explored how to write a Hello World console application using C++ /CX. Today we will develop a Hello World Application using XAML. Our Hello World app will have a simple XAML Button. Clicking the Button displays the text, Hello World on screen. Smile

As is the case, here is our MainPage.xaml


    <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
        <Button x:Name="myBtn" Width="200" Height="120" Content="Click Me" Click="myBtn_Click_1"/>
        <TextBlock x:Name="Hello" TextWrapping="Wrap" Width="200" Height="50" FontSize="20"/>

Now the actual “code behind” for MainPage.xaml. Visual Studio 2011 does an excellent job of generating the initial “ref class” for MainPage. Here is the full listing for MainPage.xaml.h

// MainPage.xaml.h
// Declaration of the MainPage class.

#pragma once

#include "MainPage.g.h"

namespace FirstApp
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public ref class MainPage sealed

        virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
        void myBtn_Click_1(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);

Finally, the full implementation of MainPage ref class, MainPage.xaml.cpp

// MainPage.xaml.cpp
// Implementation of the MainPage class.

#include "pch.h"
#include "MainPage.xaml.h"

using namespace FirstApp;

using namespace Platform;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Controls::Primitives;
using namespace Windows::UI::Xaml::Data;
using namespace Windows::UI::Xaml::Input;
using namespace Windows::UI::Xaml::Media;
using namespace Windows::UI::Xaml::Navigation;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238


/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached.  The Parameter
/// property is typically used to configure the page.</param>
void MainPage::OnNavigatedTo(NavigationEventArgs^ e)
    (void) e;    // Unused parameter

void FirstApp::MainPage::myBtn_Click_1(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
    Hello->Text = "Hello World";

Finally the output on screen

Hello World


2 thoughts on “Hello World from XAML and C++ /CX

  1. Amy

    Hi Sridhar,
    I am trying this code out as I am trying to understand how to navigate through pages via click button. When I get to the code on Mainpage.xaml.h I get an error of ‘virtual’ is not allowed.
    what can I do to rectify this?


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.