Dynamically Loading XAML


Loading XAML at run time is really simple. I wrote a small sample to load the XAML at run time and than attach the event handler with the XAML object. I created following XAML page and copied it to the debug folder.

 

<Page
    xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”
    xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”
    Title=”Page1″>
    <Grid>
        <Button Margin=”0,0,9,38″ Name=”button1″ Height=”82″ HorizontalAlignment=”Right” VerticalAlignment=”Bottom” Width=”132″>Button</Button>
    </Grid>
</Page>

 

and here is the C# code

 public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
            LoadXAMLMethod();
        }

        Button ButtoninXAML;
        public void LoadXAMLMethod()
        {
            try
            {
                StreamReader mysr = new StreamReader(“Page1.xaml”);
                DependencyObject rootObject = XamlReader.Load(mysr.BaseStream) as DependencyObject;
                ButtoninXAML = LogicalTreeHelper.FindLogicalNode(rootObject, “button1”) as Button ;
                ButtoninXAML.Click += new RoutedEventHandler(Button_Click);
                this.Content = rootObject;
            }
            catch (FileNotFoundException ex)
            {
                MessageBox.Show(ex.Message.ToString());   
            }
        }
        public void Button_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show(“Hi WPF”); 
        }
    }
}

do not forget to add following namespaces.

using System.IO;
using System.Windows.Markup; 


Comments (5)

  1. PepeChan says:

    Hi Ashish. I understand that this post is kinda old, but I would like to ask you a question.

    I have recreated your example in WPF and it Works as you say. But I tried to replicate it to Windows Phone 8 and it is not working.

    Can you point out the differences when implementing XamlReader for WP8? I cannot use XamlReader.Load(mysr.basestream) the way you do.

    Thanks in advance.

  2. Kian Mayne says:

    This is by far the most elegant way I've seen this done. Bravo!

  3. Ian.Randall says:

    Thanks again Ashish,

    I also discovered that creating the ‘subpage’ as a UserControl (with exactly the same Xaml) allows you to set the Content property on a ContentControl…

    Regards,

    Ian Randall

  4. ashish says:

    your Best bet in this scenario would be to use a Frame control on lower half of your page and set the source property of the frame to call different pages

  5. Ian.Randall says:

    Thanks Ashish,

    This sample works nicely; I wonder if you could help me with a follow-up question?

    I have placed (static) controls down half a Window, and want to dynamically load different Pages into the other half at runtime (i.e. different buttons on the left will show up different pages on the right).

    I have tried placing a ContentControl on the right-hand side of my Window, and running the following code:

      StreamReader mysr = new StreamReader("MyPage.xaml");

      DependencyObject rootObject = XamlReader.Load(mysr.BaseStream) as DependencyObject;

      ContentControl displayPage = FindName("displayPage") as ContentControl;

      displayPage.Content = rootObject;

    and I get an exception "Page can have only Window or Frame as parent."

    How do I load a xaml Page, not into a whole window, but just into part of one?

    Your help is much appreciated,

    Kind regards,

    Ian Randall