Pages

Monday 2 June 2014

WPF XAML Namespaces, Prefixes and Conventions

WPF XAML Namespaces, Prefixes and Conventions

In WPF, XAML contains namespaces for defining controls for your XAML document. You can also map other .NET namespaces to XML namespaces and use them in XAML document. There are some conventions for using prefixes with these namespaces in XAML. Lets go point to point to explore everything about XAML namespaces, prefixes used with namespaces and conventions for using prefixes in XAML.

<Window x:Class="SampleApplication.MainWindow"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Title="MainWindow" Height="350" Width="525">
  <Grid>       
  </Grid>
</Window>

1. xmlns attribute is a specialized attribute in the world of XML that is reserved for declaring namespaces.

2. The above default XAML code contains two XAML namespaces. 

http://schemas.microsoft.com/winfx/2006/xaml/presentation contains all the WPF classes, including the controls you use to build your user interface. This namespace is declared without any prefix, so this is the default namespace for the entire XAML document. Every element in XAML document, is automatically placed in this namespace unless you specify otherwise.

http://schemas.microsoft.com/winfx/2006/xaml includes various XAML utility features. This namespace is mapped to the prefix "x". That means you can apply it by placing prefix "x" before the element name.

3. The above namespaces are not URI unlike in XML.

4. You can also include .NET namespaces like System in XAML for string manipulation. Syntax for including external namespaces in XAML is:

xmlns:Prefix="clr-namespace:Namespace;assembly=AssemblyName"

For example, you can include System namespace in XAML like this:

xmlns:sys="clr-namespace:System;assembly=mscorlib"

Now you can use sys in your XAML document like this:

<sys:DateTime>10/30/2014 5:30 PM<sys:DateTime>

Similarly you can include you custom namespace that you have created in your project like this:

xmlns:local="clr-namespace:MyWPFApplication"

5. Prefix Conventions: In the above examples, I have take x, sys and local prefixes for declaring namespaces. You can take any prefix of your choice, but you should not do it because WPF says to follow this convention for prefixes while declaring XAML namespaces.

No comments:

Post a Comment

About the Author

I have more than 10 years of experience in IT industry. Linkedin Profile

I am currently messing up with neural networks in deep learning. I am learning Python, TensorFlow and Keras.

Author: I am an author of a book on deep learning.

Quiz: I run an online quiz on machine learning and deep learning.