What is xmlns
?
What role does it play in an XAML file when we create a WPF project?
What is xmlns
?
What role does it play in an XAML file when we create a WPF project?
xmlns is an XML, not necessarily XAML, construct which defines a namespace in which to resolve xml element names. Because it is defined without a qualifier, it is defining the default namespace by which an XML element name should be resolved.
In XAML you usually see the following entry. It defines the default namespace to be essentially WPF and all XML element names are hence resolved as WPF elements.
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
It's also common to see non-default namespaces such as the following.
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
This defines a qualified namespace for XAML specific elements. If you want an element or attribute name to be resolved within this namespace you should qualify it with x. For example
<StackPanel x:Name="foo" />
There are 2 name resolutions in this definition.
And you use xmlns to get a reference to your own namespaces within your XAML as well. One of the first things I do when creating a new WPF project is to add a reference to the project namespace:
xmlns:local="clr-namespace:MyWpfProject"
Now I have access to any classes I may create within my project (like IValueConverters and DataTemplateSelectors) by using the "local:" prefix
<local:BooleanToColorConverter x:Key="booleanToColorConverter" DefaultBrush="Green" HighlightBrush="Red" />
Of course, you don't have to use "local", you can name it whatever you want. And you can add references to any other namespace you need the same way.
You can also map multiple CLR namespaces together into one XML namespace by adding XmlnsDefinitionAttribute
to your assemblies. This is what the WPF team did, by mapping a lot of namespaces under System.Windows like this:
[XmlnsDefinitionAttribute(
"http://schemas.microsoft.com/winfx/2006/xaml/presentation",
"System.Windows.Controls")]
[XmlnsDefinitionAttribute(
"http://schemas.microsoft.com/winfx/2006/xaml/presentation",
"System.Windows.Ink")]
This syntax can simplify your XAML, but be careful not to have classes with the same name in the CLR namespaces you merge together.
As taken from MSDN The root element also contains the attributes xmlns and xmlns:x. These attributes indicate to a XAML processor which XML namespaces contain the element definitions for elements that the markup will reference. The xmlns attribute specifically indicates the default XML namespace.
This usage of xmlns to define a scope for usage and mapping is consistent with the XML 1.0 specification.
Hope this helps.