WPF 的「屬性元素」語法乍看匪夷所思,實則是 XAML 物件樹模型的自然延伸。本文透過 Button 與 Window 實例,說明內容模型如何將屬性外顯為子元素,以及 ContentControl 如何統一承載任意 UI 元素。
Button 繼承自 ContentControl,其 Content 屬性可接受任何物件。以下兩種寫法等價:
<!-- 簡寫:直接放入子元素 -->
<Button Width="100" Height="100">
<Image Source="tom.png" />
</Button>
<!-- 完整屬性元素語法 -->
<Button Width="100" Height="100">
<Button.Content>
<Image Source="tom.png" />
</Button.Content>
</Button>
同理可放入 TextBox、Grid 等複雜元素,實現「按鈕裝載文字輸入框」等非常規 UI。
<Button.Content> 內只能包含一個元素,嘗試放入兩個會報語法錯誤。需放入多個控件時,必須使用 Panel 衍生類(StackPanel、Grid、Canvas 等)作為容器:
<Button>
<Button.Content>
<StackPanel>
<TextBlock Text="標題" />
<Image Source="icon.png" />
</StackPanel>
</Button.Content>
</Button>
Window 同樣繼承自 ContentControl,擁有相同的內容模型:
<Window>
<Window.Content>
<Grid> ... </Grid>
</Window.Content>
</Window>
Control(如 Button)與 Container(如 Window)皆承載內容與行為。ContentControl 的類別皆具備「單一內容屬性可外顯為子元素」特性。<TypeName.PropertyName>...</TypeName.PropertyName> 將複雜物體屬性在 XAML 樹中明確化,支援巢狀物件圖構建。掌握屬性元素語法,是理解 WPF 模板、樣式與複雜 UI 組合的基石。