C++ and Metro: Basic Application
Join the DZone community and get the full member experience.
Join For Free
“Hello world”
Open the BlankPage.xaml file and start poking around with XAML. For those who haven’t used it yet, it is similar to HTML development. Scroll the code down until you find the Grid element and insert a TextBlock inside it, the final result should be:
<Grid Background="{StaticResource ApplicationPageBackgroundBrush}"> <TextBlock Text="Hello world" Margin="12,20" Style="{StaticResource SubheaderTextStyle}"/> </Grid>
The Margin property offsets the element from the default top left corner for 12 pixels from the left and 20 pixels from the top. I have used the style that comes native with all Metro applications and it is primarily used to increase the size of the text. If you want, you can set size via the FontSize attribute.
If you run the application now, you should get a black screen with the familiar “Hello world” text in the upper left corner. You define how the UI will look like in the BlankPage.xaml file, but the logic is placed in the regular BlankPage.xaml.h and BlankPage.xaml.cpp which are placed as child items for the BlankPage.xaml file in Solution Explorer.
This is a regular C++ class but something looks different. The code does not look native at all with all those strange hats around the code and ref new syntax. Although these are reminiscent of the C++/CLI syntax, these extensions are called C++/CX, which is short for Component extensions. Pure C++ is not used for developing Metro applications and using the pure WinRT would be cumbersome since everything in Metro world is actually a COM object. C++/CX extensions are supposed to cut the burden for C++ programmer with this nonstandard extension. It litters the code with AddRef and Release calls and essentially all hat pointers are nothing more than shared_ptr variant.
C++ to XAML
You can “name” the previously added TextBlock XAML element by adding the x:Name="txtHello" attribute and value. By doing this, you can refer to it from the code behind files using the following code (add it to the BlankPage::OnNavigatedTo method):
txtHello->Text = "Hello world!!!";
Run application and you should see different text like on the image below.
Although not very exciting and super-simple, think about how it is done in Win32, MFC or WTL, this is clearly easier. In the next post we will look at how to handle simple events.
Published at DZone with permission of Toni Petrina, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments