This documentation is archived and is not being maintained.

x:Code XAML Directive Element

Allows placement of code within a XAML page, which is to be compiled by any XAML processor implementation that compiles XAML as opposed to interpreting it.

   // code instructions, usually enclosed by CDATA...

x:Class Attribute must also be provided on the parent element shown as object in the syntax, and that element must be the root element in a page. The x:Code directive element must be an immediate child element of the object root element.

The code within the x:Code XAML directive element is still interpreted within the XML namespaces provided. Therefore, it is usually necessary to also enclose the code within x:Code inside a CDATA segment.

x:Code is not permitted for all possible deployment mechanisms of a XAML file. Code for WPF must still be compiled, it is not interpreted or used just-in-time. For instance, x:Code is not permitted within any XML Paper Specification (XPS) document, or loose XAML.

The correct language compiler to use for x:Code content is determined by settings and targets of the containing project that is used to compile the application.

Code declared within x:Code has several notable limitations. The code placed within x:Code will be treated by compilation to be within the scope of the partial class that is already being created for that XAML page. Therefore all code you define must be members or variables of that partial class. You cannot define additional classes, other than by nesting a class inside the partial class (that is legal, but uncommon, because nested classes cannot be referenced in XAML). Other CLR namespaces beyond the namespace being used for the existing partial class cannot be defined or added to. References to code entities outside of the partial class CLR namespace must all be fully qualified. If members being declared are overrides to the partial class overridable members, this must be specified with the language-specific override keyword. If members conflict with members of the partial class created out of the XAML page, in such a way that the compiler reports it, the XAML file will fail to be loaded or compiled.