WPF中获取系统本身自带的控件模板(XAML)

时间:2021-07-22 20:40:56

每个控件都有自己默认的模板,这是MS本身就编写好的,如果我们能够得到这些模板的XAML代码,那么它将是学习模板的最好的示例,要想获得某个控件ctrl的默认模板,请调用以下方法:

         string GetTemplateXamlCode(Control ctrl)
{ FrameworkTemplate template = ctrl.Template; string xaml = ""; if (template != null)
{ XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.IndentChars = new string(' ', );
settings.NewLineOnAttributes = true; StringBuilder strbuild = new StringBuilder();
XmlWriter xmlwrite = XmlWriter.Create(strbuild, settings); try
{
XamlWriter.Save(template, xmlwrite);
xaml = strbuild.ToString();
}
catch (Exception exc)
{
xaml = exc.Message;
}
}
else
{
xaml = "no template";
} return xaml;
}