简体   繁体   English

如何在没有 XAML 的代码中制作 WinUI 3 GUI?

[英]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".我正在将一种编程语言移植到 Windows,它具有“创建窗口”和“在该窗口中创建按钮”等命令。 The programming language itself is implemented in C++.编程语言本身在 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.我听说 Windows 上最新的推荐 UI API 是 WinUI 3,但我真的找不到任何关于如何在代码中定义 GUI 而不是从 Z8CBFD56579569C46DDED1B21D83F1BDZ3 文件加载它的好信息。

How does one create a WinUI 3 GUI in code?如何在代码中创建 WinUI 3 GUI?

This example is in C#, but it should also work in C++.这个例子在 C# 中,但它也应该在 C++ 中工作。

Perform the folling steps:执行以下步骤:

  • Create a WinUI project创建一个 WinUI 项目
  • Optional step: Remove the "MainWindow.xaml" file (and along its code behind file MainWindow.xaml.cs)可选步骤:删除“MainWindow.xaml”文件(以及文件 MainWindow.xaml.cs 后面的代码)
  • Go to the App.xaml.cs file and change the code of the OnLaunched method. Go 到 App.xaml.cs 文件并更改OnLaunched方法的代码。 See the example below请参阅下面的示例

The example code creates an instance of type Window with a StackPanel as content.示例代码创建了一个类型为Window的实例,其中StackPanel作为内容。 The StackPanel contains a TextBlock and a Button . StackPanel包含一个TextBlock和一个Button If you click on the Button, the event handling code will write someting using Debug.WriteLine .如果单击按钮,事件处理代码将使用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();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM