Quite often I get asked a very simple question: Can I skip using XAML for creating the User Interface for my app and use C++ instead? The answer is yes you can, but the bigger question is: why do you want to go down that route? I guess, to each his/her own. I must say, I do not relish the idea of writing so much C++ code. Anyways, here is our sample.
Our example today relies on the very basic Blank Metro app template that ships along with Visual Studio.
- Create a solution based on the Blank Metro app template and in the MainPage.xaml, delete the Grid section.
- Add a new function to the MainPage.xaml.h file, say, CreateUI. This function takes no parameters and returns void.
- In the MainPage.xaml.cpp, add the call to CreateUI inside the MainPage constructor, just after the InitializeComponent function call.
- Now for the cool part.
- For our sample today, we will create a Grid and add a TextBlock with the message Hello World. This is our pure-code only equivalent of the canonical Hello World samples.
- Here is the full listing of the function
auto grid = ref new Grid(); auto gridBackground = ref new SolidColorBrush(); gridBackground->Color = Windows::UI::Colors::Black; this->Content = grid; auto helloText = ref new TextBlock(); helloText->Text = "Hello World"; helloText->HorizontalAlignment = Windows::UI::Xaml::HorizontalAlignment::Center; helloText->VerticalAlignment = Windows::UI::Xaml::VerticalAlignment::Center; helloText->FontSize = 30; helloText->FontWeight = Windows::UI::Text::FontWeights::Bold; helloText->FontStyle = Windows::UI::Text::FontStyle::Oblique; auto fontFamily = ref new Windows::UI::Xaml::Media::FontFamily("Segoe UI"); helloText->FontFamily = fontFamily; auto textForeground = ref new SolidColorBrush(); textForeground->Color = Windows::UI::Colors::Green; helloText->Foreground = textForeground; grid->Children->Append(helloText);