15

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?

DK.
  • 3,173
  • 24
  • 33
Stealth Rabbi
  • 10,156
  • 22
  • 100
  • 176
  • 7
    Do nto use "XAML View", use "Blank Page" or "User Control" instead. – RavingDev Sep 19 '15 at 21:28
  • OK... that is not very intuitive, but this does work. Thanks. Feel free to make this an answer, and I will accept it. – Stealth Rabbi Sep 19 '15 at 21:29
  • 1
    Looks like your question is really "How to add code behind to a XAML view". Phrasing it as "add XAML with code behind" makes it a pretty different subject. – DK. Sep 19 '15 at 21:30
  • 1
    @DK it's semantics. "Adding a new XAML with code behind" is the same as "... add code behind to a XAML view" – Stealth Rabbi Sep 19 '15 at 21:32
  • @Stealth Rabbi not really. There is a difference between handling XAML in code behind and assigning a code behind to an existing XAML file without one. The first you handle via `XamlReader`, the 2nd with defining `x:Class` attribute on the XAML root element. Anyway, if you can change your requirement to work with a page or user control instead of a view, that could be a safer workaround. – DK. Sep 19 '15 at 21:39

1 Answers1

29

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.

Community
  • 1
  • 1
Greg Whatley
  • 1,020
  • 1
  • 13
  • 32