XAML - 堆疊面板 (StackPanel)



StackPanel 是 XAML 中一個簡單而有用的佈局面板。在 StackPanel 中,子元素可以根據 Orientation 屬性在單行中水平或垂直排列。

它通常用於建立任何型別的列表。ItemsControl(如 Menu、ListBox 和 ComboBox)使用 StackPanel。StackPanel 類的繼承層次結構如下:

StackPanel Hierarchy

屬性

序號 屬性和描述
1

Background(背景)

獲取或設定填充面板內容區域的 Brush。(繼承自 Panel)

2

Children(子元素)

獲取此 Panel 的子元素的 UIElementCollection。(繼承自 Panel。)

3

Height(高度)

獲取或設定元素的建議高度。(繼承自 FrameworkElement。)

4

ItemHeight(項高度)

獲取或設定一個值,該值指定 WrapPanel 中所有項的高度。

5

ItemWidth(項寬度)

獲取或設定一個值,該值指定 WrapPanel 中所有項的寬度。

6

LogicalChildren(邏輯子元素)

獲取一個列舉器,該列舉器可以迭代此 Panel 元素的邏輯子元素。(繼承自 Panel。)

7

LogicalOrientation(邏輯方向)

如果面板只支援單維度佈局,則為面板的方向。(繼承自 Panel。)

8

Margin(邊距)

獲取或設定元素的外邊距。(繼承自 FrameworkElement。)

9

Name(名稱)

獲取或設定元素的標識名稱。該名稱提供一個引用,以便程式碼隱藏(例如事件處理程式程式碼)可以在 XAML 處理器處理期間構造後引用標記元素。(繼承自 FrameworkElement。)

10

Orientation(方向)

獲取或設定一個值,該值指定排列子內容的維度。

11

Parent(父元素)

獲取此元素的邏輯父元素。(繼承自 FrameworkElement。)

12

Resources(資源)

獲取或設定本地定義的資源字典。(繼承自 FrameworkElement。)

13

Style(樣式)

獲取或設定此元素渲染時使用的樣式。(繼承自 FrameworkElement。)

14

Width(寬度)

獲取或設定元素的寬度。(繼承自 FrameworkElement。)

示例

以下示例顯示如何將子元素新增到 StackPanel。這是 XAML 實現,其中在具有某些屬性的 StackPanel 中建立了省略號。

<Window x:Class = "XAMLStackPanel.Window1" 
   xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" 
   Title = "MainWindow" Height = "400" Width = "604"> 
	
   <Grid> 
      <StackPanel x:Name = "myPanel"> 
         <Button Content = "Button 1" Width = "100" Height = "40" Margin = "10" /> 
         <Button Content = "Button 2" Width = "100" Height = "40" Margin = "10" /> 
         <RadioButton Content = "Radio Button 1" Width = "100"  Margin = "10" /> 
         <RadioButton Content = "Radio Button 2" Width = "100"  Margin = "10" /> 
         <RadioButton Content = "Radio Button 3" Width = "100"  Margin = "10" /> 
         <CheckBox Content = "Check Box 1" Width = "100" Margin = "10" /> 
         <CheckBox Content = "Check Box 2" Width = "100" Margin = "10" />
      </StackPanel> 
   </Grid> 
	
</Window> 

編譯並執行上述程式碼後,將產生以下輸出。您可以看到,預設情況下,子元素按垂直順序排列。您可以透過將 Orientation 屬性設定為 Horizontal 來更改排列方式。

StackPanel Output

我們建議您執行上述示例程式碼,並嘗試其他一些屬性。

xaml_layouts.htm
廣告
© . All rights reserved.