1.创建一个名为Window1.xaml的文件
内容
<DockPanel xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"> <Button Name="button1" Margin="60">Please click me. </Button> </DockPanel>
2.创建1个窗口Window1.xaml.cs
内容
using System.Windows; using System.IO; using System.Windows.Markup; using System.Windows.Controls; namespace WpfApp2 { /// <summary> /// Window1.xaml 的交互逻辑 /// </summary> public partial class Window1 : Window { private Button myButton; public Window1() { InitializeComponent(); } public Window1(string xamlFile) { //设置窗体 this.Width = this.Height = 300; this.Left = this.Top = 100; this.Title = "Dynamical loaded XAML"; //从一个XAML文件里获取XAML内容 DependencyObject rootElement; using(FileStream fs = new FileStream(xamlFile,FileMode.Open)) //文件流 { rootElement = (DependencyObject)XamlReader.Load(fs);//加载文件流 } this.Content = rootElement; myButton = (Button)LogicalTreeHelper.FindLogicalNode(rootElement, "button1"); myButton.Click += myButton_Click; } private void myButton_Click(object sender, RoutedEventArgs e) { myButton.Content = "Thank You"; } } }
3.创建一个启动类Program
内容:
using System; using System.Windows; namespace WpfApp2 { class Program:Application { [STAThread()]//指定应用程序的COM线程模型是单线程单元(sta) static void Main() { Program app = new Program();//新建一个program类 app.MainWindow = new Window1 ("Window1.xaml");// app.MainWindow.ShowDialog();//open a window } } }