Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XAML without the .xaml.cs code behind files

I'm using WPF with the Model-View-ViewModel pattern. Thus, my code behind files (.xaml.cs) are all empty, except for the constructor with a call to InitializeComponent. Thus, for every .xaml file I have a matching, useless, .xaml.cs file.

I swear I read somewhere that if the code behind file is empty except for the constructor, there is a way to delete the file from the project altogether. After searching the net, it seems that the appropriate way to do this is to use the 'x:Subclass' attribute:

<UserControl     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"     xmlns:d="http://schemas.microsoft.com/expression/blend/2008"     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"     mc:Ignorable="d"     xmlns:toolkit="http://schemas.microsoft.com/wpf/2008/toolkit"     x:Class="MyNamespace.MyClass"     x:Subclass="UserControl"     d:DesignWidth="700" d:DesignHeight="500"> 

This does the following in the generated .g.cs file:

  1. Removes the 'partial' class modifier on MyClass.
  2. Adds the class 'UserControl' in to its subclass list.

Seems perfect. Indeed, if you still have the .xaml.cs file in the build, it no longer compiles because of the missing partial--so I'm thinking this must be correct. However, if I remove the superfluous file from the build and run, the control does not get initialized correctly (it is blank). This is, I presume, because InitializeComponent() is not getting called. I see InitializeComponent is not virtual, so it seems there would be no way for the base class to call it (short of using reflection).

Am I missing something?

Thanks!

Eric

like image 976
Eric Avatar asked Dec 03 '09 17:12

Eric


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.

What is XAML CS in C#?

xaml. cs is the code-behind page for MainPage. xaml. It's where you add your app logic and event handlers. Together these two files define a new class called MainPage , which inherits from Page, in the HelloWorld namespace.

How do I find the XAML code in Visual Studio?

To open the XAML Designer, right-click a XAML file in Solution Explorer and choose View Designer. to switch which window appears on top: either the artboard or the XAML editor.


1 Answers

As another option, if you don't want to go all the way to using DataTemplates, here is an alternate approach for UserControls:

Use the x:Code attribute to embed the constructor call in the XAML:

<x:Code><![CDATA[ public MyClass() { InitializeComponent(); }]]></x:Code> 

Eric

like image 137
Eric Avatar answered Oct 21 '22 09:10

Eric