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.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: