每個控制項都有自己預設的模板,這是MS本身就編寫好的,如果我們能夠得到這些模板的XAML代碼,那麼它將是學習模板的最好的示例,要想獲得某個控制項ctrl的預設模板,請調用以下方法: ...
每個控制項都有自己預設的模板,這是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 }