Xaml语法概述及属性介绍

时间:2024-08-18 14:36:08

Xaml语法概述
1.命名空间
    xmal每个元素都对应着一个类,但是在xmal中,只提供类名是不够的,需要知道该类实在.net的哪个命名空间下面.Xaml解析器才能够正确的解析.

 1 <Page
2 x:Class="App1.MainPage"
3 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
4 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
5 xmlns:local="using:App1"
6 xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
7 xmlns:mc="http://schemas.openxmlformats.org/markup-
8
9 compatibility/2006"
10 mc:Ignorable="d"
11 Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
12
13 <Grid x:Name="RootLayout">
14
15 </Grid>
16 </Page>

上面代码两个特殊的命名空间,该命名空间会在所有的xmal文档中都有
  A:xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  B: xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
A是WP的核心命名空间,包含了大部分用来构建界面的控件类.该命名空间的声明没有使用任何命名空间的前缀,所以它是整个文档的默认命名空间,所以没有前缀的元素都自动位于该命名空间下.
?:何为命名空间前缀

B是Xaml的命名空间,它包含Xmal的实用特性,这些特性影响文档的解释方式,这个命名空间具有映射前缀x,即,可以通过在元素名称之前放置命名空间前缀,来使用
命名空间,x:Name="RootLayout"

2.对象元素
xmal文档中 每一个 自闭合 或者 成对闭合的 标签都是一个对象

<Grid></Grid>  <Button/>

3.设置属性
xmal中的属性设置,有多种语法,但是并非全部都的属性设置都是通用的
  a.使用属性语法

   <Rectangle Name="Rectag" Height="100" Width="100" Fill="Blue"

HorizontalAlignment="Left"/>

  b.使用属性元素语法
对象.属性.  属性语法的前提 该属性必须也要是Xaml 的一个对象元素

 <Rectangle Name="Rec2" Height="100" Width="100"

HorizontalAlignment="Left">
<Rectangle.Fill>
<SolidColorBrush Color="Yellow"> </SolidColorBrush>
</Rectangle.Fill>
</Rectangle>

  c.使用内容元素语法

<Border>
<Button Content="Button"/>
</Border>

这种语法 给Border 对象设置了Child属性 也就是说 我们可以直接写出一个对象

来赋值另个对象的某些属性,但是只有特别的一些属性可以用这种内容元素语法,

比如元素的Child属性,Content属性

  d.使用集合语法
如果属性的值是一个集合,就需要用集合语法去设置该属性
c# add方法可以添加的属性集合

 <Rectangle Width="200" Height="150">
<Rectangle.Fill>
<LinearGradientBrush>
<GradientStopCollection>
<GradientStop Offset="0.0" Color="Coral"></GradientStop>
<GradientStop Offset="1.0" Color="Green"></GradientStop>
</GradientStopCollection>
</LinearGradientBrush>
</Rectangle.Fill>
</Rectangle>

有些属性 既是集合属性 又是内容属性

4.附加属性

  <Canvas>
<Button Canvas.Left="50" Content="0.0"></Button>
</Canvas>

又叫做依赖属性 button 对象本来是没有Left属性的 ,但是该对象 放在Canvas布

局中 ,有了Canvas 的附加属性来设置 该对象在Canvas中的位置,即 所有Canvas

下面的对象 可以设置该属性的对象 都会有该依赖属性.

5.标记扩展

<StackPanel>
<TextBlock Text="{Binding Source={StaticResource my},Path=Per}"></TextBlock>
</StackPanel>

Binding(绑定)
StaticResource静态资源
TemplateBinding(模板绑定)
RelativeSource绑定关联源