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.

知道为什么这不起作用吗?谢谢你的帮助。

4

1 回答 1

3

我发现了我的问题。我将组件资源键与资源字典中的资源 ID 混淆了。换句话说,我的组件资源密钥与资源 ID 相同。我将我的静态属性更改为:

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

属性名称现在是RedBrushKey,而不是RedSolidBrush。关键现在正在工作。

于 2009-09-14T19:47:33.977 回答