I am building a WPF app with several assemblies, and I want to share a resource dictionary among them. That requires a ComponentResourceKey. I have built a small demo to test out the CRK, and I can't seem to get it working.
My demo has two projects, a WPF project called Demo, and a DLL called Common. The Common project has a folder called Themes. It contains my resource dictionary, generic.xaml. Here is the text of the Resource dictionary:
<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 also contains a class called SharedResources.cs. It contains a property for referencing the Brush resource in the dictionary:
public static ComponentResourceKey RedSolidBrush
{
get { return new ComponentResourceKey(typeof (SharedResources), "RedSolidBrush"); }
}
Finally, the main window in my Demo project references the brush resource to fill a rectangle:
<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>
I can't find the reason it's not working. It compiles fine in VS 2008 and Blend, but the resource isn't invoked. The only clue I have is an error message in Blend:
The Resource "{ComponentResourceKey ResourceId=RedSolidBrush, TypeInTargetAssembly={x:Type res:SharedResources}}" could not be resolved.
Any idea why this isn't working? Thanks for your help.
I found my problem. I was confusing the Component Resource Key with the Resource ID inside the resource dictionary. In other words, my Component Resource Key was the same as the Resource ID. I changed my static property to this:
public static ComponentResourceKey RedBrushKey
{
get {return new ComponentResourceKey(typeof(SharedResources), "RedSolidBrush"); }
}
The property name is now RedBrushKey, instead of RedSolidBrush. And the key is now working.
来源:https://stackoverflow.com/questions/1422538/getting-a-componentresourcekey-to-work