Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Wpf 获得一个组件ResourceKey来工作?_Wpf_Componentresourcekey - Fatal编程技术网

Wpf 获得一个组件ResourceKey来工作?

Wpf 获得一个组件ResourceKey来工作?,wpf,componentresourcekey,Wpf,Componentresourcekey,我正在用几个程序集构建一个WPF应用程序,我想在它们之间共享一个资源字典。这需要一个新的解决方案。我已经建立了一个小演示来测试CRK,但我似乎无法让它工作 我的演示有两个项目,一个名为demo的WPF项目和一个名为Common的DLL。公共项目有一个名为“主题”的文件夹。它包含我的资源字典generic.xaml。以下是资源字典的文本: <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/

我正在用几个程序集构建一个WPF应用程序,我想在它们之间共享一个资源字典。这需要一个新的解决方案。我已经建立了一个小演示来测试CRK,但我似乎无法让它工作

我的演示有两个项目,一个名为demo的WPF项目和一个名为Common的DLL。公共项目有一个名为“主题”的文件夹。它包含我的资源字典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>
public static ComponentResourceKey RedSolidBrush
{
    get { return new ComponentResourceKey(typeof (SharedResources), "RedSolidBrush"); }
}
最后,我的演示项目中的主窗口引用笔刷资源来填充矩形:

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

你知道为什么这样不行吗?谢谢你的帮助

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

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

属性名称现在是RedBrushKey,而不是RedSolidBrush。钥匙现在起作用了。

我在构建我的演示时使用了“C#2008中的Pro WPF”中的以下示例:我还对我的演示应用程序做了另一个更改。最初,我创建了一个普通的类库项目来保存共享资源字典。我删除了那个项目,并用WPF自定义控件库替换了它。我后来做了一些测试,看起来项目的类型很重要。以与我的WPF自定义控件库相同的方式设置的简单类库不起作用。该解决方案也适用于普通类库项目。本线程中描述了对类库进行改造以支持组件资源键标记扩展:我发现了一种更简单的跨程序集资源共享方法,即使用包URI。这里有解释:您确定问题出在密钥和ID相同吗?我做同样的事情,没有这样的问题。虽然我使用只读静态来避免每次都新建:publicstaticreadonlycomponentresourcekey Foo=newcomponentresourcekey(typeof(Blah),“Foo”);
public static ComponentResourceKey RedBrushKey
{
    get {return new ComponentResourceKey(typeof(SharedResources), "RedSolidBrush"); }
}