Home > English > Xaml Code Generation and XamlReader

Xaml Code Generation and XamlReader

When you are performing code generation and you would like to dynamically create some UI stuff it into a ContentPresenter, the XamlReader class comes to the rescue.  However, if you have any events that you would like to handle in your newly composed Xaml, the XamlReader class will throw an exception stating that no event handlers can be present.  I use code generation quite extensively in my applications when I have scenarios that I need user driven interfaces.  Thus, it is important to be able to have the flexibility to create Xaml on the fly and still have all the power of interacting with any event that the new UI contains as needed.

Here is a sample of Xaml taht will throw an exception when loaded by the XamlReader class:

One of the nice features that we have had since Silverlight 3 is the ability to define behaviors and triggers using a set pattern.  The good thing about this is that these behaviors and triggers are not evaluated until the given control is loaded in the VisualTree.  This is good because now we have a solution that will allow us to use the XamlReader class that has event handlers and the class does not throw an exception.

Here is a snippet of some Xaml that is created on the fly:

So the next time you are wanting to do some dynamic UI generation but also want to process events, you now have the tools to let you do so.  As an added bonus, the triggers will fire on whatever DataContext the UI is a part of.  This is nice because it supports a clean separation of concerns and follows the common Model-View-ViewModel (MVVM) pattern.

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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: