WPF **資源系統** 是樣式、模板、筆刷等可重用物件的倉庫。**樣式** 透過 Setter 批量設定屬性值,實現「一次定義,處處套用」。
<Window>
<Window.Resources>
<Style x:Key="myStyle" TargetType="{x:Type TextBlock}">
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="FontWeight" Value="Bold" />
<Setter Property="FontStyle" Value="Italic" />
</Style>
</Window.Resources>
<DockPanel>
<StackPanel>
<TextBlock Style="{StaticResource myStyle}">Name:</TextBlock>
<TextBox Text="{Binding Path=Name}" />
<TextBlock Style="{StaticResource myStyle}">Nick:</TextBlock>
<TextBox Text="{Binding Path=Nick}" />
</StackPanel>
</DockPanel>
</Window>
| 元素 | 作用 | 關鍵點 |
|---|---|---|
x:Key="myStyle" | 資源字典鍵值 | **有 Key → 顯式引用** Style="{StaticResource myStyle}" |
TargetType="{x:Type TextBlock}" | 目標類型 | Setter 的 Property 自動解析為該類型屬性;**無 Key 時 → 隱式樣式**,自動套用於範圍內所有匹配類型元素 |
Setter Property="..." Value="..." | 屬性注入 | 每個 Setter 對應一個屬性值;支援資源引用 Value="{StaticResource brushKey}" |
StaticResource | 靜態資源查找 | 編譯/載入時一次性查找,**資源必須在前方定義**;效能優於 DynamicResource |