开启左侧

WPF获取控件默认模板ControlTemplate函数

[复制链接]
绝地武士 发表于 2021-10-21 17:41:08 | 显示全部楼层 |阅读模式
  1. private string GetTemplateXamlCode(Control ctrl)
  2.         {
  3.             FrameworkTemplate template = ctrl.Template;
  4.             string xaml = "";

  5.             if (template != null)
  6.             {
  7.                 XmlWriterSettings settings = new XmlWriterSettings();
  8.                 settings.Indent = true;
  9.                 settings.IndentChars = new string(' ', 4);
  10.                 settings.NewLineOnAttributes = true;

  11.                 StringBuilder strbuild = new StringBuilder();
  12.                 XmlWriter xmlwrite = XmlWriter.Create(strbuild, settings);

  13.                 try
  14.                 {
  15.                     XamlWriter.Save(template, xmlwrite);
  16.                     xaml = strbuild.ToString();
  17.                 }
  18.                 catch (Exception exc)
  19.                 {
  20.                     xaml = exc.Message;
  21.                 }
  22.             }
  23.             else
  24.             {
  25.                 xaml = "no template";
  26.             }

  27.             return xaml;
  28.         }
复制代码

该函数的好处是在无法有效设置控件样式的时候,可以拿到原生的样式并进行适当修改,非常爽!
您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表