XAML基础(幼儿园级别)语法
XAML标签必须有结尾, 在起始标签尾部用斜杠或者使用结束标签都可以.
<Button />
<Button></Button>
上面第一个是以/>
结尾的,代表单行,很简洁。第二个用</Button>
结尾,中间可以转行并扩充很多内容,是更灵活的形式。
第一个尖括号里,Button是声明类型,后续可以跟它的属性。多个属性中间要有空格。
例如
<Button HorizontalAlignment="Left" VerticalAlignment="Top" Content="Mytext" />
<Button HorizontalAlignment="Left" VerticalAlignment="Top" Content="Mytext" ></Button>
XAML允许你在<Button></Button>
的中间插入文本内容,更简便。应用于简单文本;
例如
<Button HorizontalAlignment="Left" VerticalAlignment="Top"> MyButtonText </Button>
可以通过用标签来指定控件的属性内容, 标签名为点号连接控件名和属性名,也就是属性也可以进行多行拆分写法,这是后面嵌套的基础。
<Button>
<Button.FontWeight> Bold </Button.FontWeight>
<Button.Content> MyButtonText </Button.Content>
</Button>
这样做的好处是能够进行多个控件的嵌套
<Button>
<Button.FontWeight>Bold</Button.FontWeight>
<Button.Content>
<WrapPanel>
<TextBlock Foreground="Blue">Multi</TextBlock>
<TextBlock Foreground="Red">Color</TextBlock>
<TextBlock>Button</TextBlock>
</WrapPanel>
</Button.Content>
</Button>
可以看到中间的文本属性里嵌套了一个WrapPanel
内容(Content)属性只接受一个元素, 所以我们用WrapPanel控件把三个TextBlock控件包起来了. 这样的Panel控件有很多的用途。
进一步简化,更注重嵌套层的内容
<Button FontWeight="Bold">
<WrapPanel>
<TextBlock Foreground="Blue">Multi</TextBlock>
<TextBlock Foreground="Red">Color</TextBlock>
<TextBlock>Button</TextBlock>
</WrapPanel>
</Button>
其他注意事项:
- XAML区分大小写!因为它其实最终还是会被编译成代码,并且映射也靠变量名。
因为控件的名字最终会有对应到.NET框架下的类型(Type). 同理XAML标签的属性也区分大小写,因为这是控件的属性. - C#代码也能达到同样的效果
Button btn = new Button();
btn.FontWeight = FontWeights.Bold;
WrapPanel pnl = new WrapPanel();
TextBlock txt = new TextBlock();
txt.Text = "Multi";
txt.Foreground = Brushes.Blue;
pnl.Children.Add(txt);
txt = new TextBlock();
txt.Text = "Color";
txt.Foreground = Brushes.Red;
pnl.Children.Add(txt);
txt = new TextBlock();
txt.Text = "Button";
pnl.Children.Add(txt);
btn.Content = pnl;
pnlMain.Children.Add(btn);
当然C#的例子中可以使用更多的语法糖来写的没那么繁琐, 但你应该承认XAML要精炼的多.