XAML without the .xaml.cs code behind files XAML without the .xaml.cs code behind files wpf wpf

XAML without the .xaml.cs code behind files


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


If you follow Josh Smith's MVVM article, he uses DataTemplates for Views rather than user controls. If you put your DataTemplates into ResourceDictionaries, they don't have a code-behind at all. If you're not using the code-behind of your user control, doesn't that mean you could use a DataTemplate approach? If you do that, WPF will take care of binding your View to your ViewModel for you.


I had a discussion with a Windows Client team member at PDC about this, and right now, was told that there is no officially supported way to completely eliminate the code behind file. As you can see, you can get it to compile, but InitializeComponent() is never called, so the control doesn't get setup properly.

The x:Subclass attribute "usage is primarily intended for languages that do not support partial class declarations." It was not intended to allow this behavior (unfortunately).