Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 825
FMFF Avatar asked Jun 11 '10 14:06

FMFF


People also ask

What is code-behind in XAML?

Code-behind is a term used to describe the code that is joined with markup-defined objects, when a XAML page is markup-compiled. This topic describes requirements for code-behind as well as an alternative inline code mechanism for code in XAML.

How do I edit a XAML file?

XAML files are used in . NET programming, so they can also be opened with Microsoft's Visual Studio. However, since they're text-based XML files, you can also open one and edit one with Windows Notepad or any other text editor.

How add XAML file to WPF?

Just right click the project, choose Add -> Window and that will add a new xaml file along with its corresponding .


2 Answers

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

like image 110
Ray Burns Avatar answered Oct 20 '22 07:10

Ray Burns


I think all you have to do is create a new class file and name it exactly like your xaml with the cs extension...

test.xaml

test.xaml.cs

works in vb....

like image 45
ecathell Avatar answered Oct 20 '22 06:10

ecathell