XAML语言简介

421 阅读1分钟

什么是XAML

XAML是一种声明性标记语言。应用于.NET Core编程模型时,XAML简化了为.NETCore应用创建UI的过程。XAML文件是通常具有.xaml扩展名的XML文件。可通过任何XML编码对文件进行编码,但通常以UTF-8编码。

<StackPanel>
  <Button Content="click Me"/>
</StackPanel>

对象元素语法

对象元素语法是XAML标记语言,它通过声明XML元素来实例化CLR类或结构。此语法类似于其他标记语言(如HTML、XML)的元素语法。

  • 单标签格式:
  • 双标签格式:【可嵌入其他标签】
<Grid>
    <!--单标签-->
    <Button/>
    <!--双标签-->
    <Button>按钮</Button>
</Grid>

XAML根元素

一个XAML文件只能有一个根元素,这样才能同时作为格式正确的XML文件和有效XAML文件。对于典型WPF方案,可使用在WPF应用模型中具有突出意义的根元素(例如,页面的WindowPage)。

  • 窗体(WPF)
<Window x:Class="WPF_Boot.View.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WPF_Boot.View"
        mc:Ignorable="d"
        Title="Window1" Height="450" Width="800">
    <Grid>
       
    </Grid>
</Window>

页面(WPF)

<Page x:Class="WPF_Boot.View.Page"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
      xmlns:local="clr-namespace:WPF_Boot.View"
      mc:Ignorable="d" 
      d:DesignHeight="450" d:DesignWidth="800"
      Title="Page">

    <Grid>
        
    </Grid>
</Page>

❗在根标签下面有且只能有一个二级标签。在二级标签里面我们可以写多个三级四级标签。

WPF和XAML命名空间声明

在许多XAML文件的根标记中的命名空间声明内,通常可以看到两个XML命名空间的声明:

  • 第一个声明默认映射整个WPF客户端/框架XAML命名空间:

xmlns="schemas.microsoft.com/winfx/2006/…

  • 第二个默认映射单独的XAM命名空间,(通常)将其映射到x:前缀。

xmlns:x="schemas.microsoft.com/winfx/2006/…

这些声明之间的关系是x:前缀映射支持作为xaml语言定义一部分的内部函数,而WPF是将一种xaml用做语言的实现,并为xaml定义了其对象的词汇。