Thierry Thierry - 27 days ago 11
C# Question

Cannot compile project when declaring a XAML Resource Dictionary in code

I've got a

Resource Dictionary
called EditorResources.xaml and it contains the following code:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:editors="clr-namespace:MyCompany.Editors">

<DataTemplate x:Key="PasswordEditorDataTemplate">
</DataTemplate>
</ResourceDictionary>


But when I include this line of code in a class:

private EditorResources res = new EditorResources();


It doesn't compile my project. I doesn't display any
Errors List
view in the
.NET IDE
but when I look at my
Output
view, it displays the following error:


error CS0246: The type or namespace name 'EditorResources' could not be found (are you missing a using directive or an assembly reference?)


But, I don't believe the reference is missing as both the resource dictionary and class are in the same project (same level) and I can clearly see the
EditorResources
type highlighted as
Type
and
IntelliSense
kicks in as expected when I hit my '.' key and it displays properties relevant to a
Resource Dictionary
i.e.
.MergeDictionaries
, etc...

UPDATE:

if like me, you've stored your resource dictionary (editorresources.xaml) in a sub-folder (Editors), and your assembly is called 'MyCompany.Activity.Shared' for example, don't forget to include the sub-folder in the component's part so that when you call the code provided by @DrewNoakes, you can call the following without any problems:

var res = new ResourceDictionary
{
Source = new Uri("/MyCompany.Activity.Shared;component/editors/editorresources.xaml",
UriKind.RelativeOrAbsolute)
};


Once you have your object, you can access your DataTemplates or other via code.

Answer

Seems like you have a EditorResources.xaml file but not a corresponding EditorResources.xaml.cs file.

In this case, the type your XAML file defines is ResourceDictionary. If you wish to have a subclass of that, you need to define the partial backing class and add the relevant attributes in the XAML to link them together.

If you don't need any C# code behind the scenes, just load the ResourceDictionary directly.

Some code like this might help:

var dict = new ResourceDictionary
{
    Source = new Uri("/YourAssemblyName;component/EditorResources.xaml",
                     UriKind.RelativeOrAbsolute)
}