Below was Blank App (C++/WinRT) project.
I am trying to create a TextBlock and set its Text (x,y) property "Left" and "Top" dynamically from MainPage.cpp and display it on runtime XAML form.
However, for testing, code below able to compile successfully and at the runtime result, no TextBlock component "Hellow World!" is shown.
Is there anything wrong or missing ?
namespace winrt::...::implementation
{
MainPage::MainPage()
{
InitializeComponent();
Process();
}
void MainPage::Process()
{
winrt::hstring hs = L"Hello World!";
TextBlock tbx;
tbx.FontFamily( Windows::UI::Xaml::Media::FontFamily(
L"Segoe UI Semibold" ) );
tbx.FontSize(72.0);
tbx.Foreground( SolidColorBrush( Colors::Orange() ) );
tbx.VerticalAlignment( VerticalAlignment::Center );
tbx.TextAlignment( TextAlignment::Center );
tbx.Text( hs );
Window window = Window::Current();
window.Content( tbx );
window.Activate();
}
}
Please advise.
The underlying problem is a XAML layout issue. Here's a little demo that should put you on the right track. I modified your MainPage above to look like this:
MainPage::MainPage()
{
InitializeComponent();
winrt::hstring hs = L"Hello World!";
TextBlock tbx;
tbx.FontFamily(Windows::UI::Xaml::Media::FontFamily(
L"Segoe UI Semibold"));
tbx.FontSize(72.0);
tbx.Foreground(SolidColorBrush(Colors::Orange()));
tbx.VerticalAlignment(VerticalAlignment::Center);
tbx.TextAlignment(TextAlignment::Center);
tbx.Text(hs);
this->Content().as<Panel>().Children().Append(tbx);
}
The XAML page looks like this:
<Page ... >
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center">
<Button x:Name="myButton" >Click Me</Button>
</StackPanel>
</Page>
The basic idea is that you want to add the control to a panel that is managing layout on the main page, rather than adding it to the top level Window object. It may be instructive to play around in the designer a bit to get the desired look, then restructure it into equivalent code using C++ /WinRT.
Ben