今天我来给大家推荐一个非常实用的库——xamltreedump。这个库可以将 xaml 树上的元素转换成 json 字符串,非常适合用于 ui 单元测试。
首先,我们需要通过 NuGet 工具来安装 XamlTreeDump 库。
假设我们有一个 UI 界面代码如下:
<page background="{ThemeResource ApplicationPageBackgroundThemeBrush}" mc:ignorable="d" x:class="WholebaycarNowawnawka.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="using:WholebaycarNowawnawka" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <grid> <textblock>欢迎访问我博客 https://blog.lindexi.com 里面有大量 UWP WPF 博客</textblock> </grid> </page>
在后台代码中,我们可以使用 VisualTreeDumper.DumpTree 方法来获取 JSON 字符串:
public MainPage() { InitializeComponent(); Loaded += MainPage_Loaded; } private void MainPage_Loaded(object sender, RoutedEventArgs e) { var xaml = VisualTreeDumper.DumpTree(this, null, Array.Empty<string>(), new AttachedProperty[0]); }
通过上述代码,我们可以得到如下的 JSON 字符串:
{ "XamlType": "WholebaycarNowawnawka.MainPage", "Background": "#FFFFFFFF", "BorderBrush": null, "BorderThickness": "0,0,0,0", "Clip": null, "CornerRadius": "0,0,0,0", "FlowDirection": "LeftToRight", "Foreground": "#FF000000", "HorizontalAlignment": "Stretch", "Margin": "0,0,0,0", "Padding": "0,0,0,0", "RenderSize": [1200, 900], "VerticalAlignment": "Stretch", "Visibility": "Visible", "children": [ { "XamlType": "Windows.UI.Xaml.Controls.Grid", "Background": null, "BorderBrush": null, "BorderThickness": "0,0,0,0", "Clip": null, "CornerRadius": "0,0,0,0", "FlowDirection": "LeftToRight", "HorizontalAlignment": "Stretch", "Margin": "0,0,0,0", "Padding": "0,0,0,0", "RenderSize": [1200, 900], "VerticalAlignment": "Stretch", "Visibility": "Visible", "children": [ { "XamlType": "Windows.UI.Xaml.Controls.TextBlock", "Clip": null, "FlowDirection": "LeftToRight", "Foreground": "#FF000000", "HorizontalAlignment": "Stretch", "Margin": "0,0,0,0", "Padding": "0,0,0,0", "RenderSize": [1200, 900], "Text": "欢迎访问我博客 https://blog.lindexi.com 里面有大量 UWP WPF 博客", "VerticalAlignment": "Stretch", "Visibility": "Visible" } ] } ] }
更多详细信息,请参考 asklar/XamlTreeDump: A UWP library to produce and compare XAML tree dumps useful for visual end-to-end testing。
本文的所有代码都已放置在 GitHub 和 Gitee 上,欢迎大家访问。
本文会经常更新,请阅读原文:https://www.php.cn/link/8b23716b7bceb1123ebe2457a756dc13。
本作品采用知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议进行许可。欢迎转载、使用、重新发布,但务必保留文章署名林德熙(包含链接:https://www.php.cn/link/3ef430bcac19166ddf205dd8cdf4edca。
无盈利,不卖课,做纯粹的技术博客。
以上就是win10 uwp 使用 XamlTreeDump 获取 XAML 树元素内容的详细内容,更多请关注php中文网其它相关文章!
Windows激活工具是正版认证的激活工具,永久激活,一键解决windows许可证即将过期。可激活win7系统、win8.1系统、win10系统、win11系统。下载后先看完视频激活教程,再进行操作,100%激活成功。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号