win10 uwp 使用 XamlTreeDump 获取 XAML 树元素内容

今天我来给大家推荐一个非常实用的库——xamltreedump。这个库可以将 xaml 树上的元素转换成 json 字符串,非常适合用于 ui 单元测试。

首先,我们需要通过 NuGet 工具来安装 XamlTreeDump 库。

假设我们有一个 UI 界面代码如下:


    
        欢迎访问我博客 https://blog.lindexi.com 里面有大量 UWP WPF 博客
    

在后台代码中,我们可以使用 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(), 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./link/8b23716b7bceb1123ebe2457a756dc13。

本作品采用知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议进行许可。欢迎转载、使用、重新发布,但务必保留文章署名林德熙(包含链接:https://www./link/3ef430bcac19166ddf205dd8cdf4edca。

无盈利,不卖课,做纯粹的技术博客。