Add Code Behind to a Resource Dictionary

I recently used a Resource Dictionary and wanted to be able to tweak the xaml components on it behind the scenes. This can be accomplished fairly easily:

  1. In your project add a new class file. Give it the same name as the xaml.
  2. In the newly created file override the contents of the namespace with this code:
  3. Next, go to your <ResourceDictionary> tag in the xaml file. Add this property with the appropriate namespace and name: x:Class="namespace.classname"

Now the two should be linked up. In Visual Studio, however, they will not be nested like normal xaml files. This bugged me. I read online that the csproj file can be edited in notepad to accomplish this. I tried and for some reason I couldn’t get it to take. I did have success with VSCommands. It is an install that adds extra features to Visual Studio. Once installed select the xaml and cs with your mouse in the tree. Right-click and choose Group Items. Choose the xaml as the root item to be conventional. Now Solution Explorer should show them as paired.