Extensible Application Markup Language (XAML) 隨 .NET Framework 3.0 引入,並非獨立程式語言,而是一種「聲明式物件圖構建語言」。它將 UI 結構、資源、動畫、繫結等以 XML 形式描述,經由 XAML 編譯器轉換為 BAML (Binary Application Markup Language) 嵌入組件,並在運行時由 WPF 框架解析實例化對應的 CLR 物件。關鍵在於:每一個 XAML 元素對應一個 CLR 類型,每一個屬性對應該類型的 Dependency Property 或 CLR Property,這使得 XAML 與 C#/VB.NET 程式碼擁有完全等價的表達能力。
<UserControl x:Class="MediaPlayer.Page"
xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml">
xmlns (預設命名空間) 透過 XmlnsDefinitionAttribute 硬編碼映射至 System.Windows.Controls、System.Windows.Shapes 等核心命名空間。xmlns:x 引入 XAML 語言內建類型(x:Class、x:Key、x:Static 等)。xmlns:local="clr-namespace:MyApp;assembly=MyApp" 映射專案內類型。<Button>
<Button.Content>
<Rectangle Width="40" Height="40" Fill="Black"/>
</Button.Content>
</Button>
TypeName.PropertyName 形式明確指定屬性掛載目標,支援任意複雜巢狀物件樹,是 ControlTemplate、DataTemplate、Style 等進階功能的基石。
XAML 屬性值本質皆為字串,TypeConverter 負責轉換。以 Button.Background="White" 為例:
Background 為 Brush 類型,尋找其 TypeConverterAttribute 指向 BrushConverter。BrushConverter.ConvertFrom("White") 再委派 ColorConverter 解析顏色名稱,最終建立 SolidColorBrush(Colors.White)。<Button.Background><SolidColorBrush Color="White"/></Button.Background>。自訂型別僅需標記 [TypeConverter(typeof(MyConverter))] 即可享受同樣便利。
以 {MarkupExtensionName Argument} 形式出現,常見內建延伸:
| 延伸 | 用途 | 範例 |
|---|---|---|
StaticResource | 靜態資源查找 | Background="{StaticResource brushKey}" |
DynamicResource | 動態資源查找(支援運行時變更) | FontSize="{DynamicResource {x:Static SystemFonts.MessageFontSizeKey}}" |
Binding | 資料繫結 | Text="{Binding Path=Name, Mode=TwoWay}" |
TemplateBinding | 控制項模板內繫結至 TemplatedParent | Background="{TemplateBinding Background}" |
x:Static | 引用靜態欄位/屬性 | Color="{x:Static SystemColors.ControlBrushKey}" |