Search code examples
wpfxaml

Why use the ComponentResourceKey MarkupExtension?


I've written a lot of WPF styles and templates but never used the ComponentResourceKey markup extension. I've never understood why I would need it.

I obviously read this in the docs

Defines and references keys for resources that are loaded from external assemblies. This enables a resource lookup to specify a target type in an assembly, rather than an explicit resource dictionary in an assembly or on a class.

But I'm still not understanding what this buys me. Either way I have to specify the target type.

For example, reading up on creating a custom view for the ListViewControl, I came across this article which uses a Style that starts off like this:

<Style x:Key="{ComponentResourceKey 
      TypeInTargetAssembly={x:Type l:PlainView},
      ResourceId=myPlainViewDSK}" 
       TargetType="{x:Type ListView}" 
       BasedOn="{StaticResource {x:Type ListBox}}"
       >

If this were my project, why would I not want to just start it off something like this?

<Style x:Key="MyViewKey" TargetType="{x:Type l:PlainView}"

Solution

  • If you're making a project that no one else will use, then either approach is fine.

    However, imagine you're making a control library, that other people will use. Now, consider the resource lookup behavior for StaticResource and DynamicResource.

    When you use a string-based x:Key, it is possible for there to be a "collision" with resource keys. What if you use MyViewKey in your control library, and your user uses that key as well? The user's key will be used - not yours.

    Sometimes, this is desired - it allows the user to override your styles. Other times, it's not.

    ComponentResourceKeys create an unambiguous resource key.