新建一个WPF项目,将App.Xaml和MainWindow.xaml删除
未经编译的XAML文件内容如下
<DockPanel xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Button Name="Button1" Margin="60">Please Click Me!</Button>
</DockPanel>
C#代码如下 ```java using System.IO; using System.Windows; using System.Windows.Controls; using System.Windows.Markup;
namespace 项目7 { ///
public MainWindow(string xamlFile)
{
//设置窗体
this.Width = 800;
Height = 450;
Left = Top = 150;
Title = "Dynamically Loaded XAML";
//从外部文件获取XAML的内容
DependencyObject rootElement;
using (FileStream fs = new FileStream(xamlFile, FileMode.Open))
{
rootElement = XamlReader.Load(fs) as DependencyObject;
}
Content = rootElement;
btn = LogicalTreeHelper.FindLogicalNode(rootElement, "Button1") as Button;
btn.Click += btn_Click;
}
void btn_Click(object sender, RoutedEventArgs e)
{
btn.Content = "Thank you!";
}
}
}
4. 再新建个Program.cs类,作为启动程序:
```java
using System;
using System.Windows;
namespace 项目7 {
class Program:Application {
[STAThread]
static void Main()
{
Program app=new Program();
app.MainWindow=new MainWindow("Window1.xaml");
app.MainWindow.ShowDialog();
}
}
}
项目包含的类
运行后的效果
- 点击后的效果