Reputation: 1693
I have a default template defined for one of my classes. It works correctly and is applied as I'd expect, but I am using an attached property (detailed here, actually) for which I have to specify a DataTemplate
. I have been unable to find an acceptable way of specifying my default template in XAML.
My data template looks something like this:
<DataTemplate DataType="{x:Type myNS:MyType}">
....
</DataTemplate>
So far I have attempted to specify it like this
attached:property.MyDataTemplate="{StaticResource {x:Type myNS:MyType}}"
but this throws an exception at runtime ("Cannot find resource named 'My.Full.NameSpace.MyType'. Resource names are case sensitive.").
I've done enough looking around to know that other people have similar problems but I haven't been able to find a decent solution. I am considering simply maintaining a duplicate DataTemplate
with an x:Key
so I can point at it. Is there a better way?
UPDATE:
Alright - it's been pointed out that this does work if you use DynamicResource
instead of StaticResource
. This does not make sense to me.
I've read a fair bit on DynamicResource vs StaticResource (among other thing, I read this thread). Here's what I do know:
If I specified a x:Key
instead of a DataType
I can use this template as a StaticResource
.
When the page loads the template is in the dictionary and can be retrieved in code
var myTemplate = this.Resources[new DataTemplateKey(typeof(MyType))];
Can anyone explain what's happening here?
Upvotes: 3
Views: 1873
Reputation: 199
I guess, the problem because of your DataTemplate
has DataTemplateKey
with type myNS:MyType
, but property.MyDataTemplate="{StaticResource {x:Type myNS:MyType}}"
tries to find resource with string key matching your type full name.
Instead of using "{StaticResource {x:Type myNS:MyType}}"
you should use:
"{StaticResource {DataTemplateKey {x:Type myNS:MyType}}}"
or its full equivalent:
"{StaticResource ResourceKey={DataTemplateKey DataType={x:Type myNS:MyType}}}"
.
Also, you don't need DynamicResource
in this case.
Upvotes: 1
Reputation: 17380
Give this a try: (Switch StaticResource
to DynamicResource
)
attached:property.MyDataTemplate="{DynamicResource {x:Type myNS:MyType}}"
My guess for the reason why this works:
This answer gives a good difference between StaticResource
and DynamicResource
. I'm guessing this Default template data isn't available when StaticResource
tries to retrieve it(during the loading of the XAML) which isn't the case for DynamicResource
Upvotes: 1