为什么使用ComponentResourceKey“无法解析资源”?

时间:2014-03-02 12:17:37

标签: c# wpf xaml resourcedictionary componentresourcekey

我正在尝试使用ComponentResourceKey重用自定义资源,但它不起作用,我收到此警告:

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

以下是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>

ResourceLibrary/CustomResources.cs

namespace ResourceLibrary{
    public class CustomResources{}
}

用法如下(在SomeOtherProject/MyWindow.xaml中):

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

为什么“资源无法解决”?

请注意,我知道SO问题“Getting a ComponentResourceKey to Work?”,但在这种情况下的问题是代码隐藏,我无论如何都缺乏...

1 个答案:

答案 0 :(得分:1)

使用ComponentResourceKey时,请确保xmlns前缀与.dll类文件不同

((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" />

我创建了这个字典类来嵌入/合并我的.dll字典

<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>

然后在我的实际窗口/ usercontrol中,我将window / usercontrol资源与上面的资源字典合并,并且它工作了

希望这会有所帮助

相关问题