提示:以下是本篇文章正文内容,下面案例可供参考
1.在MainWindow.xaml.cs里面输入以下代码:
using System.Windows; using System.Windows.Markup; using System.IO; namespace WpfApp4 { public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } public MainWindow(string xamlFile) { this.Width = this.Height = 285; this.Left = this.Top = 100; this.Title = "Dynamically Loaded XAML"; //从一个XAML文件里获取XAML内容 DependencyObject rootElement; using (FileStream fs = new FileStream(xamlFile, FileMode.Open)) { rootElement = (DependencyObject)XamlReader.Load(fs); } this.Content= rootElement; } } }
2.创建Program.cs类
using System; using System.Windows; namespace WpfApp4 { class Program:Application { [STAThread()] static void Main() { Program app=new Program(); app.MainWindow= new MainWindow("Window1.xaml"); app.MainWindow.ShowDialog(); } } }
3.在bin/Debug文件里插入Window1.xaml
<DockPanel xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"> <Button Name="button1" Margin="30">Please click me.</Button> </DockPanel>