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

此生再无相见时 提交于 2019-12-08 16:31:37

问题


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.


回答1:


As far as I know without Version Control there is no way to revert back if the project has been saved. You should look into putting your code on Version Control.

At this point I would consider recreating your xaml file, copying your old code in, then deleting your events in XAML and recreating them, once you recreate them it will reproduce the code behind.




回答2:


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




回答3:


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




回答4:


I know i am late to the party...but this is what just worked for me. IF you are in VisualStudio you can: 1. Exclude all the files you want to link from the project 2. Include just the .xaml file. For me that included the .xaml.cs file as well as code behind.

Note: Make sure the compile relationship is correct in the .csproj file. It should look like this:

<ItemGroup>
  <Compile Include="App.xaml.cs">
    <DependentUpon>App.xaml</DependentUpon>
  </Compile>...

To see that text you will need to unload the project and then edit the .csproj file inside any texteditor. VS 2015 also lets you edit that file if you rightclick on the unloaded .csproj file.

Hope this helps someone.



来源:https://stackoverflow.com/questions/3023496/accidentally-deleted-the-code-behind-for-an-xaml-file-how-do-i-add-the-code-beh

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!