C#-在运行时加载xaml文件

C#-在运行时加载xaml文件,c#,wpf,xaml,runtime,C#,Wpf,Xaml,Runtime,我在C#中有一个WPF应用程序 我有一个MainWindow类,它继承自System.Windows.Window类 接下来,我的磁盘上有一个要在运行时加载的xaml文件: <Window x:Class="MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

我在C#中有一个WPF应用程序

我有一个
MainWindow
类,它继承自
System.Windows.Window

接下来,我的磁盘上有一个要在运行时加载的xaml文件:

<Window x:Class="MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="I want to load this xaml file">
</Window>


如何在运行时加载该xaml文件?换句话说,我希望我的MainWindow类完全使用提到的xaml文件,因此我不想使用MainWindow的方法
AddChild
,因为它向窗口添加了一个子窗口,但我想替换
窗口的参数。如何实现这一点?

默认情况下,WPF应用程序在VS模板中有一个StartupUri参数:

<Application x:Class="WpfApplication2.App"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         StartupUri="MainWindow.xaml">
</Application>
要用另一个窗口“替换”此窗口,请执行以下操作:

  • 使用mainWindow.hide()隐藏此窗口
  • 使用XamlReader读取personal.xaml,它为您提供加载的xaml的窗口实例
  • 将其分配给mainWindow(如果需要)并调用Show()来显示它
您是否希望应用程序的实例“主窗口”包含应用程序实例的成员,这当然是您的选择

总之,整个技巧是:

  • 隐藏主窗口
  • 加载窗口实例
  • 显示您的窗口实例
简短回答: -不可以,您不能从
窗口
内部更换
窗口
。在一个
窗口
派生的对象中,您无法访问任何内容,该对象显示“嘿,用另一个窗口替换所有内容”

详细回答: -然而,你可以做一些像这样愚蠢的事情:

private void ChangeXaml()
{
    var reader = new StringReader(xamlToReplaceStuffWith);
    var xmlReader = XmlReader.Create(reader);
    var newWindow = XamlReader.Load(xmlReader) as Window;    
    newWindow.Show();
    foreach(var prop in typeof(Window).GetProperties())
    {
        if(prop.CanWrite)
        {
            try 
            {
                // A bunch of these will fail. a bunch.
                Console.WriteLine("Setting prop:{0}", prop.Name);
                prop.SetValue(this, prop.GetValue(newWindow, null), null);
            } catch
            {
            }
        }
    }
    newWindow.Close();
    this.InvalidateVisual();
}

试试Xaml阅读器。另请参阅,谢谢你的提示,但我之前已经看过了该页面-所有内容都有详细描述,仅根据那篇文章,我无法将
窗口
参数替换为磁盘上xaml文件中的一个参数-我只需将新的子项添加到其中。“窗口参数”是什么意思?顶部标记是对类的描述,该类在处理xaml后成为Window的实例。如果您想替换MainWindow的实例,那么问题是谁持有这个实例,即变量在哪里更改?然后,您可以使用XamlReader的结果更改此变量。彼得,为了您自己的利益,如果您希望人们在将来努力帮助您,您应该阅读、评论并投票支持建议的答案。@thomas:非常感谢,这正是我想要的。太好了,非常感谢。正如您所提到的,关键是将
窗口
实例替换为一个新实例。
private void ChangeXaml()
{
    var reader = new StringReader(xamlToReplaceStuffWith);
    var xmlReader = XmlReader.Create(reader);
    var newWindow = XamlReader.Load(xmlReader) as Window;    
    newWindow.Show();
    foreach(var prop in typeof(Window).GetProperties())
    {
        if(prop.CanWrite)
        {
            try 
            {
                // A bunch of these will fail. a bunch.
                Console.WriteLine("Setting prop:{0}", prop.Name);
                prop.SetValue(this, prop.GetValue(newWindow, null), null);
            } catch
            {
            }
        }
    }
    newWindow.Close();
    this.InvalidateVisual();
}