Matthias Shapiro

I need fewer hobbies

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.

This entry was posted in Advanced Tutorial, listview, templates, WPF, XAML. Bookmark the permalink.

0 Responses to Tip For Finding Resources for a Control in generic.xaml

  1. You’re welcome. Thanks for blogging about this stuff.

  2. Matthias Shapiro

    Good catch.

    Fixed it… thanks!

  3. Is there a typo in this post? The ResourceId does not match the key used in code.

    “MyCustomControlTemplate” != “MyCustomTemplate”

    It’s entirely possible that I’ve missed something. I’ve dropped by this page while trying to learn a little more about resources keys. Nice blog btw.