C# - LOAD XAML FILE AT RUNTIME

Jeet Verma

Total Post:110

Points:776
Posted by  Jeet Verma
WPF 
WPF
 1441  View(s)
Ratings:
Rate this:

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"

    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>                                      

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?

  1. Sumit Kesarwani

    Post:378

    Points:2694
    Re: C# - load xaml file at runtime

    Hi Jeet,

    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();

    }

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!