如何让ComponentResourceKey正常工作?

3
我正在构建一个包含多个程序集的WPF应用程序,并且我想在它们之间共享资源字典。这需要使用ComponentResourceKey。我已经构建了一个小型演示来测试CRK,但好像无法使其正常工作。
我的演示有两个项目,一个名为Demo的WPF项目和一个名为Common的DLL。 Common项目有一个名为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:Common" >

    <SolidColorBrush 
        x:Key="{ComponentResourceKey TypeInTargetAssembly={x:Type local:SharedResources}, ResourceId=RedSolidBrush}" 
        Color="Red"/>

</ResourceDictionary>

Common还包含一个名为SharedResources.cs的类。它包含一个用于引用字典中 Brush 资源的属性:

public static ComponentResourceKey RedSolidBrush
{
    get { return new ComponentResourceKey(typeof (SharedResources), "RedSolidBrush"); }
}

最后,在我的Demo项目中,主窗口引用刷子资源来填充一个矩形:

<Window x:Class="ComponentResourceKeyDemo.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:res="clr-namespace:Common;assembly=Common"
    Title="Window1" Height="300" Width="300">
    <Grid>
        <Rectangle Height="100" Width="100" Stroke="Black" Fill="{DynamicResource {ComponentResourceKey TypeInTargetAssembly={x:Type res:SharedResources}, ResourceId=RedSolidBrush}}" />
    </Grid>
</Window>

我无法找到它不工作的原因。它在VS 2008和Blend中编译得很好,但资源没有被调用。我唯一的线索是在Blend中出现了一个错误消息:

The Resource "{ComponentResourceKey ResourceId=RedSolidBrush, TypeInTargetAssembly={x:Type res:SharedResources}}" could not be resolved.

有任何想法为什么这不起作用吗?感谢您的帮助。

1个回答

4

我找到了问题所在。我把组件资源键和资源字典内部的资源ID混淆了。换句话说,我的组件资源键和资源ID相同。我将静态属性更改为:

public static ComponentResourceKey RedBrushKey
{
    get {return new ComponentResourceKey(typeof(SharedResources), "RedSolidBrush"); }
}

属性名称现在是RedBrushKey,而不是RedSolidBrush。并且该键现在已经生效。


1
我还对我的演示应用程序进行了另一个更改。最初,我创建了一个普通的类库项目来保存共享资源字典。我删除了该项目,并用 WPF 自定义控件库替换了它。我进行了一些后期测试,发现项目类型很重要。与我的 WPF 自定义控件库相同设置的简单类库将无法工作。 - David Veeneman
该解决方案也适用于普通的类库项目。将类库改造以支持组件资源键标记扩展的方法在此线程中描述:https://dev59.com/FEvSa4cB1Zd3GeqPeGdN#2094123 - David Veeneman
我发现了一种更简单的跨程序集资源共享方法,使用 Pack URIs。这里有详细说明:http://stackoverflow.com/questions/2095031/wpf-sharing-resources-across-assemblies - David Veeneman
1
你确定键和ID相同是问题所在吗?我也做了完全相同的事情,但没有像这样的问题。虽然我使用只读静态来避免每次都新建它:public static readonly ComponentResourceKey Foo = new ComponentResourceKey(typeof(Blah), "Foo"); - scobi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接