C# - load xaml file at runtime

I have a WPF application in C#.

I have a MainWindow class which inherits from a System.Windows.Window class.

Next I have an xaml file on my disk which I want to load at runtime:

<Window x:Class="MainWindow"
    Title="I want to load this xaml file">

How can I load that xaml file at runtime? In other words, I want my MainWindow class to use exactly the mentioned xaml file, so I do not want to use the method AddChild of the MainWindow because it adds a child to the window, but I want to replace also that Window parameter. How can I achieve this?

Last updated:3/3/2015 2:13:38 AM

1 Answers

Anonymous User
Anonymous User

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