aardio 文档

aardio 范例: 加载 .NET WPF / XAML 界面

// WPF 控件
import win.ui;
/*DSG{{*/
var winform = win.form(text="aardio 加载 .NET WPF / XAML 界面";right=759;bottom=469)
winform.add(
custom={cls="custom";text="自定义控件";left=133;top=137;right=740;bottom=450;db=1;dl=1;dr=1;dt=1;z=1}
)
/*}}*/

/*
XAML 的配置与使用繁琐且难以驾驭。
如果必须要用 WPF,建议用 C# 写到程序集里,
然后用 aardio 导入 .NET 程序集并加载 WPF 控件。

不要盲从网上宣扬这类 XML 界面库的文章,复杂界面用 web.view 是更好的选择。
*/

// 加载相关程序集并导入 .NET 命名空间
import System.Windows.Forms.Integration;// WPF 必须导入这个库
//import System.Windows.Markup;//可省略,上面的库已导入 WPF 几个常用的命名空间

// 创建 ElementHost
var elementHost = System.Windows.Forms.Integration.ElementHost(winform.custom);

// 定义 XAML 字符串(注意必须包含 xmlns 命名空间声明)
var xamlString = `
<Grid xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <StackPanel VerticalAlignment="Center" HorizontalAlignment="Center">
        <TextBlock x:Name="txtTitle" Text="来自 XAML 的标题" FontSize="20" Margin="10"/>
        <Button x:Name="btnClick" Content="点我试试" Width="100" Height="30"/>
    </StackPanel>
</Grid>
`;

// 使用 XamlReader 解析 XML,也可以用外部程序集中的类创建 wpfGrid
var wpfGrid = System.Windows.Markup.XamlReader.Parse(xamlString);

// 通过 FindName 找到 XAML 中定义的控件对象
var btn = wpfGrid.FindName("btnClick");
var txt = wpfGrid.FindName("txtTitle");

// 绑定事件
btn.add_Click(function(sender,e){
    txt.Text = "按钮已被点击!";
    winform.msgbox("你点击了从 XAML 加载的按钮");
});

// 也可以用纯代码创建 WPF 按钮控件
/*
var wpfButton = System.Windows.Controls.Button();
wpfButton.Content = "这是 WPF 按钮";
wpfButton.FontSize = 20;

var brush = System.Windows.Media.SolidColorBrush();
brush.Color = System.Windows.Media.Color.FromArgb(255, 100, 149, 237); // 蓝色
wpfButton.Background = brush;
*/

// 设置到 ElementHost 中,
elementHost.Child = wpfGrid;

winform.show();
win.loopMessage();
Markdown 格式