纯代码创建,不需要创建界面,创建WPF工程后,直接复制代码就可以使用。
当你手头没有Blend,又不记得以下这段代码,但是又想浏览控件模版的时候,就可以直接复制拿来用了。
public partial class MainWindow : Window
{
ListBox lbox;
TextBox tbox;
Grid grid;
public MainWindow()
{
InitializeComponent();
InitializeControl();
LoadControlTemplate();
}
/// <summary>
/// 创建界面
/// </summary>
private void InitializeControl()
{
grid = new Grid();
ColumnDefinition col1 = new ColumnDefinition();
ColumnDefinition col2 = new ColumnDefinition();
col1.Width = GridLength.Auto;
grid.ColumnDefinitions.Add(col1);
grid.ColumnDefinitions.Add(col2);
//List
lbox = new ListBox();
lbox.SelectionChanged += (a, b) => { ShowControlTemplate(); };
//TextBox
tbox = new TextBox();
tbox.VerticalScrollBarVisibility = ScrollBarVisibility.Auto;
tbox.HorizontalScrollBarVisibility = ScrollBarVisibility.Auto;
grid.Children.Add(lbox);
grid.Children.Add(tbox);
Grid.SetColumn(lbox, 0);
Grid.SetColumn(tbox, 1);
this.Content = grid;
}
private void LoadControlTemplate()
{
Type type = typeof(System.Windows.Controls.Control);
List<Type> controlType = new List<Type>();
System.Reflection.Assembly assembly = System.Reflection.Assembly.GetAssembly(typeof(System.Windows.Controls.Control));
foreach (Type item in assembly.GetTypes())
{
if (item.IsSubclassOf(type) && !item.IsAbstract && item.IsPublic)
{
controlType.Add(item);
}
}
lbox.ItemsSource = controlType;
}
private void ShowControlTemplate()
{
try
{
Type type = (Type)lbox.SelectedItem;
System.Reflection.ConstructorInfo info = type.GetConstructor(Type.EmptyTypes);
Control control = (Control)info.Invoke(null);
control.Visibility = Visibility.Collapsed;
grid.Children.Add(control);
ControlTemplate template = control.Template;
System.Xml.XmlWriterSettings setting = new System.Xml.XmlWriterSettings();
setting.Indent = true;
StringBuilder sb = new StringBuilder();
System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(sb, setting);
System.Windows.Markup.XamlWriter.Save(template, writer);
tbox.Text = sb.ToString();
grid.Children.Remove(control);
}
catch (Exception ex)
{
tbox.Text = ex.Message;
}
}
}
截图: