We pay for user submitted tutorials and articles that we publish. Anyone can send in a contributionLearn More
Have you ever tried to create a DataTemplate for a Generic Class? During last week I had to battle this issue and it is allot more complicated then it sounds. As far as I can tell Creating DataTemplates for Generic classes is impossible. There is some kind of workaround but it is not all that good. OK lets get down to business. This is the class we are trying to template
The code for the Window was this:
So far so good. The problem starts in the Xaml, since we want to bind a control to a single class our binding expression is this:
The problem is in the DataTemplate. In order for it to work we have to specify the type of the class, but what is the type of the class? We can’t write GenericClass<T> because the "<" and ">" will close the tags and what the hell is T (this is the Xaml compiler talking, not me), We can’t write GenericClass<string> because the "<" and ">" will cause problems again.
Here is when I stopped and started to search in Google. A futile effort because when you enter a search phrase with Generic, Class and DataTemplate together you will get tons of tutorials about how to create DataTemplates for Generic Collections. After trying for an hour I gave up and had a brilliant idea! why not use the Binding Expression from before and NO template to see what is printed out to the screen! here is what I got:
Interesting… I guess the number after the "`" represents the number of parameter and inside the brackets you see the type. Great, I thought to myself and quickly typed it in the DataType field of the DataTemplate so the DataTemplate looked like this:
only to get the following error from Visual Studio:
Error 1 Cannot find the type ‘data:GenecicClass.GenericClass`1[System.String]’. Note that type names are case sensitive. Line 7 Position 23. D:\VS2005Projects\BlogTests\GenericClass\GenericClass\Window1.xaml 7 23 GenericClass
I tried almost any combination of the name and no success…
I did not give up and played around with it some more. Despite Shahar’s post about DataTemplates for Interfaces not being supported. I decided to try using an interface. This was the code:
And the Template:
And still nothing. Same result as before.
I was this close on loosing the Generic Class but I decided to sit down and think of the problem at hand.
Here is me thinking…
It seems that there is no possibility to define the DataType, so I will have to specify a template for the ContentControl without specifying the Type. The only option is the Template Attribute which accepts ControlTemplates. I Quickly created a ControlTemplate and specified the Template attribute to point to it:
And check this out! I got exactly what I wanted:
All that work for a crappy window with "Tests" written in it…
Hope it helps
Copyright © 2012 Dev102.com
Breeze : Designed by Amit Raz and Nitzan Kupererd