DockPanel 將 WinForms 的 Dock 屬性提升為**容器級佈局策略** — 子元素宣告停靠邊緣,容器按順序分配剩餘空間。適合**頁面級大區塊佈局** (頂部工具列、底部狀態列、左側導航、右側屬性、中間工作區)。
<DockPanel LastChildFill="True">
<Button DockPanel.Dock="Left">Left</Button>
<Button DockPanel.Dock="Right">Right</Button>
<Button DockPanel.Dock="Top">Top</Button>
<Button DockPanel.Dock="Bottom">Bottom</Button>
<Button>Fill (Center)</Button> <!-- 最後一個,自動填滿 -->
</DockPanel>
子元素**按 XAML 聲明順序**依次停靠,每個元素佔據當前剩餘空間的邊緣條帶:
Dock="Left" → 佔左側條帶,剩餘空間縮減。Dock="Top" → 佔剩餘空間頂部條帶。順序不同,佈局截然不同 — 設計時需精心安排聲明順序。
<DockPanel LastChildFill="True">
<ToolBarTray DockPanel.Dock="Top">...</ToolBarTray> <!-- 頂部工具列 -->
<StatusBar DockPanel.Dock="Bottom">...</StatusBar> <!-- 底部狀態列 -->
<TreeView DockPanel.Dock="Left" Width="200">...</TreeView> <!-- 左側導航 -->
<ContentControl /> <!-- 中央工作區,自動填滿 -->
</DockPanel>
| 場景 | 推薦 | 理由 |
|---|---|---|
| 頁面級大區塊 (Header/Footer/Sidebar/Content) | DockPanel | 語義清晰、順序直觀、LastChildFill 零配置 |
| 表格式對齊、複雜比例分配、跨行跨列 | Grid | 精確控制、共享尺寸組、附加屬性靈活 |
| 簡單線性堆疊 | StackPanel | 輕量、無網格開銷 |
DockPanel 是「全局觀」佈局容器 — 一眼望去,頁面骨架清晰可見。