xaml
cs
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Windows;using System.Windows.Controls;using System.Windows.Data;using System.Windows.Documents;using System.Windows.Input;using System.Windows.Media;using System.Windows.Media.Imaging;using System.Windows.Navigation;using System.Windows.Shapes;using System.Reflection;using System.Xml;using System.Windows.Markup;namespace ControlTemplateBrowser{ ////// Interaction logic for MainWindow.xaml /// public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); this.Loaded += new RoutedEventHandler(MainWindow_Loaded); } void MainWindow_Loaded(object sender, RoutedEventArgs e) { Type controlType=typeof(Control); ListderivedTypes = new List (); //Search all the types in the assembly where the control class is defined Assembly assembly = Assembly.GetAssembly(typeof(Control)); foreach (Type type in assembly.GetTypes()) { //only add a type of the list if it's a control, a concrete class, //and public if (type.IsSubclassOf(controlType)&&!type.IsAbstract&&type.IsPublic) { derivedTypes.Add(type); } } //sort the types. the custom typeComparer class orders types //alphabetically by type name derivedTypes.Sort(new TypeComparer()); lstTypes.ItemsSource = derivedTypes; } private void lstTypes_SelectionChanged(object sender, SelectionChangedEventArgs e) { try { //get the selected Type type = (Type)lstTypes.SelectedItem; //Instantiate the type ConstructorInfo info = type.GetConstructor(System.Type.EmptyTypes); Control control = (Control)info.Invoke(null); //Window win = control as Window; //if (win != null) //{ // // Create the window (but keep it minimized). // win.WindowState = System.Windows.WindowState.Minimized; // win.ShowInTaskbar = false; // win.Show(); //} //else //{ // Add it to the grid (but keep it hidden). control.Visibility = Visibility.Collapsed; grid.Children.Add(control); //} // Get the template. ControlTemplate template = control.Template; // Get the XAML for the template. XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; StringBuilder sb = new StringBuilder(); XmlWriter writer = XmlWriter.Create(sb, settings); XamlWriter.Save(template, writer); // Display the template. txtTemplate.Text = sb.ToString(); // Remove the control from the grid. //if (win != null) //{ // win.Close(); //} //else //{ grid.Children.Remove(control); //} } catch (Exception err) { txtTemplate.Text = "<<>Error generating template:" + err.Message+ ">"; } } }}
TypeComparer
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Collections;namespace ControlTemplateBrowser{ public class TypeComparer : IComparer{ public int Compare(Type x, Type y) { if (x == null || y == null) throw new ArgumentException("参数不能为空"); if (x.Name.CompareTo(y.Name) != 0) { return x.Name.CompareTo(y.Name); } else { return 0; } } }}