Thierry Thierry - 2 months ago 12
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=""

<DataTemplate x:Key="PasswordEditorDataTemplate">

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
but when I look at my
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
type highlighted as
kicks in as expected when I hit my '.' key and it displays properties relevant to a
Resource Dictionary
, etc...


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

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


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