Be careful with Data Template markup

This one is rather for WPF beginners but even after working on WPF for few years, I happened to make this mistake and overlooked it. So just wanted to highlight it for benefit of others…..

When you define a DataTemplate, make sure that you define the x:Key attribute before any other attributes, otherwise it will not get picked up because of the ForwardOnly usage policy of static resource.  I tried the following:

<DataTemplate DataType="wpfApplication1:ViewModel1" x:Key="DataTemplate1" >

and it gave me the famous error:  “Cannot find resource named ‘DataTemplate2’. Resource names are case sensitive.”

Just by changing the order of the x:Key attribute and putting it before DataType attribute, solved this error. So be careful 🙂

Have a nice day!