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=http://schemas.microsoft.com/winfx/2006/xaml/presentation申明的命名空間加上一個前綴,那麼代碼必須修改成這樣

 

<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"



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章