How to Load XAML Files dynamically at runtime without compiling your WPF XAML code?

Sometimes, you need to add controls to your WPF window at runtime. This can be done easily within WPF application as it enables you to display uncompiled XAML code. The below example demonstrates this feature by loading a button at runtime from an XML file and wiring up a click event to it to display a message when clicked.

public Window1()

private void myButton_Click(object sender, RoutedEventArgs e)
  MessageBox.Show("I have been clicked");

private void LoadRuntimeControls()
  //Load button from XML file
  FileStream fileStream = new FileStream(@"c:\RuntimeContent.xml", FileMode.Open);
  DependencyObject dependencyObject = XamlReader.Load(fileStream) as DependencyObject;
  this.Content = dependencyObject;

  //Find the button and wireup a click event
  Button myButton = LogicalTreeHelper.FindLogicalNode(dependencyObject, "btnOnTheFly") as Button;
  myButton.Click+=new RoutedEventHandler(myButton_Click);

Please note that loading XAML dynamically is not as efficient as compiling it. However, sometimes, it is necessary to load it dynamically at runtime.