This example is in C#, but it should also work in C++.
Perform the following steps:
- Create a WinUI project
- Optional step: Remove the "MainWindow.xaml" file (and along its code behind file MainWindow.xaml.cs)
- Go to the App.xaml.cs file and change the code of the
OnLaunched
method. See the example below
The example code creates an instance of type Window with a StackPanel
as content. The StackPanel
contains a TextBlock
and a Button
. If you click on the Button, the event handling code will write something using Debug.WriteLine
.
/// <summary>
/// Invoked when the application is launched normally by the end user. Other entry points
/// will be used such as when the application is launched to open a specific file.
/// </summary>
/// <param name="args">Details about the launch request and process.</param>
protected override void OnLaunched(Microsoft.UI.Xaml.LaunchActivatedEventArgs args)
{
// The original version of the method just contained these two lines:
//m_window = new MainWindow();
//m_window.Activate();
m_window = new Window();
StackPanel stackPanel = new StackPanel();
TextBlock textBlock = new TextBlock();
textBlock.Text = "Text of the TextBlock";
Button button = new Button();
button.Content = "Click Me";
button.Click += (object sender, RoutedEventArgs e) => { Debug.WriteLine("Button clicked"); };
stackPanel.Children.Add(textBlock);
stackPanel.Children.Add(button);
m_window.Content = stackPanel;
m_window.Activate();
}