开发者

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

开发者 https://www.devze.com 2023-01-03 16:23 出处:网络
Instead of excludin开发者_如何学Pythong 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.

Instead of excludin开发者_如何学Pythong 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.


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


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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消