Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make a WinUI 3 GUI in code without XAML?

I'm porting a programming language to Windows that has commands like "create a window" and "create a pushbutton in that window". The programming language itself is implemented in C++.

I hear the newest, recommended UI API on Windows going forward is WinUI 3, but I couldn't really find any good information on how to define a GUI in code instead of loading it from XAML files.

How does one create a WinUI 3 GUI in code?

like image 761
uliwitness Avatar asked Nov 15 '22 17:11

uliwitness


1 Answers

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();
    }
like image 194
Martin Avatar answered Dec 14 '22 22:12

Martin