WPF中获取系统本身自带的控件模板(XAML)
每个控件都有自己默认的模板,这是MS本身就编写好的,如果我们能够得到这些模板的XAML代码,那么它将是学习模板的最好的示例,要想获得某个控件ctrl的默认模板,请调用以下方法:
1 string GetTemplateXamlCode(Control ctrl) 2 { 3 4 FrameworkTemplate template = ctrl.Template; 5 6 string xaml = ""; 7 8 if (template != null) 9 { 10 11 XmlWriterSettings settings = new XmlWriterSettings(); 12 settings.Indent = true; 13 settings.IndentChars = new string(' ', 4); 14 settings.NewLineOnAttributes = true; 15 16 StringBuilder strbuild = new StringBuilder(); 17 XmlWriter xmlwrite = XmlWriter.Create(strbuild, settings); 18 19 try 20 { 21 XamlWriter.Save(template, xmlwrite); 22 xaml = strbuild.ToString(); 23 } 24 catch (Exception exc) 25 { 26 xaml = exc.Message; 27 } 28 } 29 else 30 { 31 xaml = "no template"; 32 } 33 34 return xaml; 35 }