XAML基础(幼儿园级别)语法

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>



其他注意事项:

  1. XAML区分大小写!因为它其实最终还是会被编译成代码,并且映射也靠变量名。
    因为控件的名字最终会有对应到.NET框架下的类型(Type). 同理XAML标签的属性也区分大小写,因为这是控件的属性.
  2. 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要精炼的多.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值