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"



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