2.1 XAML语法入门
什么是XAML?
XAML(eXtensible Application Markup Language)是WPF的核心标记语言,用于以声明式方式定义用户界面。它通过XML语法描述对象层次结构,实现了界面设计与业务逻辑的分离。
基础语法结构
<Window x:Class="MyApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Main Window" Height="450" Width="800">
<Grid>
<Button Content="Click Me" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Grid>
</Window>
关键元素解析:
- 根元素:通常为Window/Page/UserControl等顶级容器
- xmlns声明:
- 默认命名空间:WPF核心控件
x:命名空间:XAML语言特性(如x:Class, x:Name)
- 属性设置:
- 直接属性(Title/Height/Width)
- 复杂属性(通过属性元素语法)
对象元素语法
<!-- 等价于 new Button() -->
<Button />
<!-- 带属性的对象 -->
<Button Content="OK" Background="LightBlue"/>
属性设置方式
- 特性语法(Attribute Syntax):
<Button Content="Submit"/> - 属性元素语法(Property Element Syntax):
<Button> <Button.Content>Submit</Button.Content> </Button> - 内容属性语法(Content Property Syntax):
<Button>Submit</Button>
特殊语法特性
- 标记扩展(Markup Extensions):
<Button Content="{Binding UserName}"/> - 类型转换器(Type Converters):
<Rectangle Fill="Blue"/> <!-- 自动转换为SolidColorBrush -->
代码示例:完整XAML文档
<Window x:Class="XAMLDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="XAML Demo" Height="350" Width="525">
<StackPanel>
<TextBlock Text="Enter your name:" Margin="5"/>
<TextBox x:Name="txtName" Width="200" Margin="5"/>
<Button Content="Greet" Click="Button_Click" Margin="5"/>
</StackPanel>
</Window>
最佳实践建议
- 保持XAML整洁,避免内联复杂逻辑
- 使用命名规范(x:Name采用驼峰命名法)
- 合理使用注释:
<!-- 主操作按钮 --> <Button Content="Save"/> - 优先使用资源定义样式和模板
常见错误处理
- 缺少命名空间声明
- 拼写错误的属性名
- 未闭合的标签
- 不正确的嵌套层次
注意:XAML编译时会生成.g.cs文件,可通过"转到定义"查看生成的代码
