Why "the resource could not be resolved" using ComponentResourceKey?

2.3k views Asked by At

I'm trying to reuse custom resources using ComponentResourceKey, but it doesn't work, and I get this warning:

Warning 12 The resource "{ComponentResourceKey ResourceId=SadTileBrush, TypeInTargetAssembly={x:Type res:CustomResources}}" could not be resolved.

Here is the ResourceLibrary/Themes/generic.xaml:

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:ResourceLibrary">
    <ImageBrush x:Key="{ComponentResourceKey TypeInTargetAssembly={x:Type local:CustomResources},
                        ResourceId=MyBrush}"
        ImageSource="ResourceLibrary;component/../../myImage.jpg">
    </ImageBrush>
</ResourceDictionary>

And the ResourceLibrary/CustomResources.cs:

namespace ResourceLibrary{
    public class CustomResources{}
}

The usage is as follows (in SomeOtherProject/MyWindow.xaml):

<Button Background="{DynamicResource {ComponentResourceKey
                    TypeInTargetAssembly={x:Type res:CustomResources}, 
                    ResourceId=MyBrush}}"> Some text </Button>

Why "the resource could not be resolved" ?

Please note that I'm aware of the SO question "Getting a ComponentResourceKey to Work?", but the problem in that case was in a code-behind, which I lack anyway...

1

There are 1 answers

0
Max Mazur On

When you use ComponentResourceKey make sure that the xmlns prefix is different from the .dll class file

((DLL = 'Local' - this class = 'res')

<Button Background="{DynamicResource {ComponentResourceKey TypeInTargetAssembly={x:Type res:CustomResources}, ResourceId=SadTileBrush}}" Padding="5" Margin="5" FontWeight="Bold" 
            FontSize="14" Content="A Resource From ReusableResourceLibrary" />

I created this dictionary class to embed / merge my .dll dictionary

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

<ResourceDictionary.MergedDictionaries>
    <ResourceDictionary Source="pack://application:,,,/ReusableResourceLibrary;component/Dictionary1.xaml" />
</ResourceDictionary.MergedDictionaries>
<ImageBrush x:Key="DicTileBrush" TileMode="Tile" ViewportUnits="Absolute" Viewport="0 0 50 50" ImageSource="../Resources/Images/Smiley_Happy.png" Opacity="0.3" />
</ResourceDictionary>

and then inside my actualy window/usercontrol, i merged the window/usercontrol resources with the above resource dictionary and it worked

hope this helps