Revision #90

You are currently reviewing an older revision of this page.
Go to current version

The purpose of this article is to highlight some of the many uses for building XAML dynamically at run time.  These techniques are extremely powerful.

Particularly if you ever write code which is building UI controls, styles, triggers or pretty much anything you can do in XAML then these techniques can save you an awful lot of time.
This is one of those areas which is really exciting  - so long as you can possibly do it in XAML the limitations are your imagination. 

                                   

Work In Progress - Please do not edit


Introduction


Most of the techniques which follow leverage two facts:
  • XAML is xml so you can manipulate and build it like you would do xml
  • You can use XamlReader.Load ( or Parse ) at run time to dynamically build what you can do with XAML in the designer.
This is a huge subject and an approach used by relatively few WPF developer - if this is new to you then you definitely want to give it a go.

Rather than repeat two versions of everything a fair part of the explanation will be in samples on the Gallery.  That allows them to be self explanatory if someone comes across them separately and this article can be long rather than massive.

This article explains the concepts and broad strokes.
The samples go into detail.

Loading a Flat File as a Resource Dictionary


Even beginners will probably be familiar with merging Resource Dictionaries in app.xaml.

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="Dictionary1.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

Perhaps rather surprisingly, where you use a Resource Dictionary like that you can use an uncompiled flat file.  This is potentially very powerful since your Views could be templated and loaded in that a way.

This offers the potential to re-skin an application at a fundamental level without re-compiling or re-distributing.
Particularly if you're writing and delivering multi client software packages this has HUGE potential.
Not excited yet?
You can do that merge in a window, control or wherever you can put a .Resources.
And of course if you wanted to you could over-ride resources by having a resource dictionary merged in a more immediate scope.
This setting a style for all Datagrids in app.xaml but a different one for a specific Datagrid by loading another Resource Dictionary in it's parent Window.Resources. 
It's also very simple to use.  The limiting factor is thinking up what to put in the resource dictionaries..
Read more about it in the sample here.

Changing the Unchangeable


The usual way to change something dynamically in WPF is to Bind style or Template.
There are some things which you can't set in a style - like a style for example !
Templates can change some more things but can be inconvenient if you're looking for a way to apply a style to controls which already have content.
One work round would of course be to introduce a content control with a template.
That can also be impractical at times.
That leaves us with Binding.
You cannot bind anything on a freezable though.
This is a particular nuisance where you would like to bind attributes like the Value, To or From on an animation.
A specific example of this sort of thing is a re-usable animation that will animate the height of a FrameworkElement between zero and it's usual height on a condition.
This is useful to add a bit of pizzazz to a UI where the user selects adds or manipulates items and you want them or a container they're switched into to grow and shrink.
A particular complication to this is that many such elements will have no specific height - they will usually just grow to the size their contents demand.  There is no height to work with until they're full of stuff.
Read more about this in the sample here.

Flexible Composition


You can compose your entire view and content using these techniques.  This can be.
  • Built on the fly by composing pieces of xml 
  • Read from some pre configured piece of xml
The pieces of xml used to load into XAML can be
  • Read off disk and can get there by self configure, install, file copy or ftp
  • Built into the exe or library you are loading
At an extreme an application could consist of a main page which is entirely empty. This is used as a shell, to be then filled with content dynamically.
In such a system you would have a number of viewmodels - these could be loaded from dynamically downloaded and discovered library or set of libraries.
By one of the options above, the view is composed and an appropriate viewmodel instantiated and presented to the view as the datacontext.

There are two samples, the first composes the view to be used dynamically by the second.

Awkward Bindings/Data


Many requirements have a fixed list of fields and they're in a collection of a fairly simple object with a value property translating into a column.  You're looking at one Vehicle or a list of Vehicles.
When the data you are to show is a bit more dynamic this can be rather a problem.
If you have a variable set of columns to show then one way to do that is build your columns in code.
If these are simple columns then it's a bit of a nuisance but still practical.
If these columns have formatting then the code to do this can start to get rather quite long.
Instead of writing code to generate bindings we can create a template and dynamically build using that.

The sample for this section shows sales data for the last 6 complete months.   It takes sales data which has been pivotted into a collection of Salesmen, each of which has a collection of sales stats, one per month for the last 12 months.
The XAML for the Datagrid is built as xml and parsed to give a WPF Datagrid.
You can see the sample here.



Dynamic Column List




This is a H3



This is a H4


To do:

User configurable markup
Awkward Bindings/Data

Insert attribute
Clone and add binding
Add repeating pattern
XSLT