首先由一个未加载的XAML类,需要把这个文件放到bin/debug文件夹下要不会找不到,或者传递参数带上路径,下面的例子是使用相对路径传的参数例如:
<DockPanel xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Button Name="button1" Margin="60">Please click me.</Button>
</DockPanel>
Mainwindow中
<Window x:Class="WpfApplication3.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApplication3"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
</Grid>
</Window>
把WPF自带的APP.XAML 删除了,新创建一个Progream类引导启动
Progream.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace WpfApplication3
{
class Progream : Application
{
[STAThread()]
static void Main()
{
Progream app = new Progream();
app.MainWindow = new MainWindow("../../123/Window1.xaml");
app.MainWindow.ShowDialog();
}
}
}
MainWindow.xaml.cs 重写一个MainWindow具体代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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.IO;
using System.Windows.Markup;
namespace WpfApplication3
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private Button myButton;
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;
myButton = (Button)LogicalTreeHelper.FindLogicalNode(rootElement, "button1");
myButton.Click += myButton_Click;
}
private void myButton_Click(object sender, RoutedEventArgs e)
{
myButton.Content = "Thank you";
}
}
}