Accidentally deleted the code behind for an Xaml file. How do I add the code behind again?

FMFF picture FMFF · Jun 11, 2010 · Viewed 8.2k times · Source

Instead of excluding it, by mistake, I deleted the .cs code behind file for an Xaml file. Now, I don't know how to add the code behind.

This Window is empty with no UI controls on it. "View Code" is disabled and I can't see the Events (lightning bolt icon) anywhere for this xaml.

Please help.

Answer

Ray Burns picture Ray Burns · Jun 12, 2010

There are two required steps and one optional:

  1. Create a new .xaml.cs file in the same directory (Right-click project -> Add -> New Item -> Class)
  2. Copy in the boilerplate code from some other .xaml.cs in your project, changing the class name appropriately (eg. copy the "using" directives, class declaration, and constructor including the InitializeComponent call).
  3. (optional) Edit your .csproj file to add a <DependentUpon> element below your <Compile> element for the .xaml.cs file so that it will appear "inside" the .xaml file not simply below it. If you are updating project to be edited with Blend (v4), this third step is required, not optional, in order to use the inspector to add events to controls.

To easily edit the .csproj file:

  1. Right-click the project and select "Unload Project"
  2. Right-click the project node again and select "Edit [projectname].csproj"
  3. Edit the XML, then close the file
  4. Right-click the project node again and select "Reload Project"

If you're using VB.NET, everything the same, just replace "cs" with "vb".