Understanding the XAML namespaces

An XAML namespace is an extension to the XML namespace syntax, providing you the concept to use markup entities from referenced assemblies or different modules. When you create a new Windows UserControl or any other XAML pages, you will see that there are two XAML namespace declarations within the root tag of the XAML.

The first namespace xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" maps the client/framework-specific XAML namespaces as default.

The second namespace declaration xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" maps a different XAML namespace with the prefix x:, to provide you intrinsic supports to the XAML language definition. It defines many commonly used features, which are required for basic WPF applications. For example, the x:Class attribute in the root element of the XAML file defines the code behind the class name that you want to use as a partial class:

You can also map XAML namespaces to an assembly using a series of tokens in an xmlns declaration. The syntax has two token names: clr-namespace and assembly. For example, xmlns:controls="clr-namespace:Packt.KunalChowdhury.Demo.Controls;assembly=MyAssembly".

The first token, that is, the clr-namespace defines the CLR namespace of the public element that you want to access from the second token, that is, assembly. The second token should pass the name of the assembly (without the file extension) and not the path of it. Once you have defined it, you can access the public type/element within that XAML.

Let's discuss this with a simple example:

 <Window x:Class="MyWpfApplication.MainWindow" 
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
   xmlns:controls="clr-namespace:Packt.KunalChowdhury.Demo.Controls;
assembly=MyAssembly" Title="Main Window" Height="350" Width="525"> <Grid> <controls:MyUserControl /> </Grid> </Window>

Here we have defined the XMLNS namespace to clr-namespace:Packt.KunalChowdhury.Demo.Controls;assembly=MyAssembly and assigned a prefix controls, so that we can access the public type MyUserControl, which is already available in it under the Packt.KunalChowdhury.Demo.Controls namespace with the <controls:MyUserControl /> XAML tag.

You can omit the assembly if the clr-namespace referenced is being defined within the same assembly as the application. Alternatively, you can specify assembly= without defining any string token.