Aline’s Tech Blog

All my geekness is here :-)

WPF Data Templates: Several views for 1 class July 28, 2008

Filed under: WPF — Aline @ 10:00 am
Tags: , , ,

Today i’m going to introduce you a WPF concept called Data Templating.

When I started WPF, i felt lost, and i didn’t know how to do. I wanted to use my scholar knowledge about object-oriented programming, make inheritance relationships between usercontrols, like in windows forms or Java.

My problem was that I had 1 user control (basically, a grid with several labels), which displays the contents of a collection in the labels. My graphic control had to be used in different configurations. Depending on the configuration, the data was not displayed in the same way, but the business code (data collection, grid) was the same.

The first idea i had, using my little UML model, was to make inheritance: a parent grid user control, with several children chosen depending on the configuration. In this way, with WPF, everything was coded into a .VB file. It was quite inappropriate. Moreover it was hard to realize this inheritance, because WPF didn’t allow me to display my parent Grid control into the designer…

And then, I posted on MSDN forums, WPF disciples, I started reading this book, and understood i wasn’t thinking the right way.

The right way, for this particular case, is to use Data Templates.

Data Templating allows you to have 1 class that contains all your business code (here, my data collection), and to consider your graphic interface as a template (here a grid template), that you define in a resource dictionary.
This is very easy to do this with Expression Blend. You can define several templates to apply them to the class.

After this you can define a Template Selector class to select your template programatically, or select it dynamically. The data template for a custom user control is defined by the ContentTemplate attribute. In my solution, i have bound this attribute to the selected item of a combobox.

The template elements (labels,…) can be bound (in xaml ResourceDictionary) to the collection items. And the graphics can be completely different.

To use data templates, here are some cool links which helped me a lot, including code samples and HowTos:

http://msdn2.microsoft.com/en-us/library/ms752339.aspx
http://www.contentpresenter.com/index.php
http://msdn.microsoft.com/en-us/library/ms742521.aspx

 

Leave a Reply