Skip to content

Tip For Finding Resources for a Control in generic.xaml

I’ve recently be working on changing the ControlTemplate of a GridViewColumnHeader in a custom ListView that we’ve been working on. (The ListView was rewritten for sorting, so that’s why it had to be custom.)

One of the things we had to do was swap out ControlTemplates so that we could display a caret to indicate ascending or descending lists. We ended up deciding on ControlTemplates over DataTemplates because the DataTemplates would only work for ListViews that had no custom DataTemplates for the headers. We’re doing all sorts of crazy stuff with our headers and we need to preserve our DataTemplates, so this wasn’t an option.

In any case, I was having no luck finding the resource when I named it this way:

<ControlTemplate x:Key="MyCustomControlTemplate" TargetType="{x:Type GridViewColumnHeader}">

I was using the following code to try and find the resource.

ControlTemplate myNewTemplate = (ControlTemplate)Resources["MyCustomTemplate"];

However, we were able to solve the problem by naming the resource this way

<ControlTemplate x:Key="{ComponentResourceKey TypeInTargetAssembly={x:Type local:MyCustomListView}, ResourceId=MyCustomControlTemplate}"
        
TargetType="{x:Type GridViewColumnHeader}">

And then using this code to access it.

ComponentResourceKey myCustomTemplateKey = new ComponentResourceKey(typeof(SortableListView), "MyCustomControlTemplate");
ControlTemplate myNewTemplate = (ControlTemplate)this.TryFindResource(myCustomTemplateKey);

Just thought I’d pass it along.