How to add a new XAML View with code behind

Stealth Rabbi picture Stealth Rabbi · Sep 19, 2015 · Viewed 17.4k times · Source

I am using VS 2015, creating a Univerasl App. I want to create a new view (XAML). I can right click, Add > XAML > XAML View, and the XAML gets created with the name and location that I want.

But, how can I create a code behind here, e.g. MyNewView.xaml.cs, and "link it up" as a child node in my solution explorer?

Answer

Greg Whatley picture Greg Whatley · Sep 24, 2015

As RavingDev said:

Do not use "XAML View", instead use "Blank Page" or "User Control".


On a side note, if you want to manually create a code file and link it with anything else (i.e. Visual Studio automatically links .cs and .xaml on creation), you'll have to edit the project's XML code.

Assume you created a XAML view/page/control named MyView.xaml and a separate C# file named MyView.xaml.cs, and they're unlinked (this can also happen if you add files directly into the Solution Explorer). To link them, you will have to edit your project's internal code. First, save and quit Visual Studio. Second, find your project file (<project name>.csproj). Open it with a text editor, such as Notepad++, VS Code, or Atom (not Visual Studio). Move down the file until you see ItemGroup elements. There are a few of them, but the one that contains Compile elements is the right one. Add the following code somewhere inside that element:

<Compile Include="MyView.xaml.cs">
  <DependentUpon>MyView.xaml</DepenedentUpon>
</Compile>

Do this for every file you want to link. If everything was done correctly, you can save the file and open it back up in Visual Studio. Your files should now be linked in the Solution Explorer.