原文: XAML的命名空間 一個最簡單的XAML例子
<Window x:Class="WpfApplication1.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>
xmlns特征的文法格式如下:xmlns[:可選的映射字首]="名稱空間"
xmlns後可以跟一個可選的映射字首,之間用冒号分隔,如果沒有寫可選映射字首,就意味着所有來自這個名稱空間的标簽都不用加字首,這個沒有映射字首的名稱空間稱為“預設名稱空間”,預設名稱空間隻能有一個。上面的例子中,Window和Grid都屬于 xmlns=
http://schemas.microsoft.com/winfx/2006/xaml/presentation聲明的預設命名空間,而Class特征來自于
xmlns:x=
http://schemas.microsoft.com/winfx/2006/xaml申明的命名空間,如果給 xmlns=
申明的命名空間加上一個字首,那麼代碼必須修改成這樣
<n:Window x:Class="WpfApplication1.MainWindow"
xmlns:n="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<n:Grid>
</n:Grid>
</n:Window>
在C#中,如果要使用System.Windows.Controls名稱空間裡的Button類,需要先把包含System.Windows.Controls美林歌城空間的程式集PresentationFramework.dll通過添加引用的方式引用到項目中,然後再在C#代碼的頂端輸入using System.Windows.Controls;
在XAML如果需要使用Button類,也需要先添加對程式集的引用,然後在根元素的起始标簽中寫上一句:xmlns:c="clr-namespace:System.Windows.Controls;assembly=PresentationFramework"
x:Class這個屬性的作用是當XAML解析器将包含它的标簽解析成C#類後的類名,用Windows SDK自帶的工具IL反彙程式設計式對編譯出來的exe進行反彙編,可以發現生成了MainWindow類
在XAML中引用名稱空間的文法是:
xmlns:映射名="clr-namespace:類庫中名稱空間的名字;assembly=類庫檔案名"
例如:MyLibrary.dll中包含Common和Control兩個名稱空間,而且已經把這個程式集引用進WPF項目,那麼在XAML中對于這兩個名稱空間,XAML中的引用會是:xmlns:common="clr-namespace:Common;assembly=MyLibrary" xmlns;control="clr=namespace:Control;assembly=MyLibrary"