This blog describes how TemplateSelector in WPF can be used to dynamically modify contents of the UI. This is particularly useful in a common scenario many ISV's need to support: ability of 3rd parties and users to extend the ISV's data model with their own data columns.
For example, the original application may include a Product table with some columns (e.g. Id, Name, etc.). However, application's users may want to extend that definition to include additional columns. One of the issues that presents is using the data in UI: the UI provided by the ISV obviously has no notion of the new data columns. WPF, through template selector functionality allows the ISV to include these items in their UI.
One of the options on data binding is the specification of a template selector. Template selector is a custom class derived from DataTemplateSelector, which implements a method returning a DataTemplate given reference to the data that needs to be presented. The method can return an existing data template but it can also construct a new data template dynamically and return it. It is the last option that is particularly useful in the ISV scenario. The custom selector can dynamically discover the new columns added by the user, possibly collect additional meta-data about them (from SQL or some other proprietary mechanism used by the ISV) and return a data template, which provides a mapping of the data columns to WPF UI elements.
The attached sample shows how this can be done. For simplicity's sake the sample generates all its source data. Note that the recommended way of creating the new data template is by constructing xaml and using XamlReader. (The alternative, using the DataTemplate class, populating it with data, etc. is not recommended).