這篇文章先說明子控制項常見的版面配置方式:
- Width and Height - 控制項的寬和高, 如果設成Auto的話, 它們的值會變成Double.NaN, 這時後你就必須透過 ActualHeight 和ActualWidth(唯讀屬性)來取得畫面配置後的高和寬. 注意: Width / Height的值是可以改變的, 但ActualHeight / ActualWidth是不行的.
- MinWidth, MaxWidth, MinHeight, and MaxHeight -控制項的最小/最大寬和高; 注意: 如果你同時在元件中設定了Height, ActualHeight, MinHeight和MaxHeight, 如果Height落在MinHeight和MaxHeight 之間, Height的優先權為最高, 但是如果衝突發生時, 它們的優先順序如下(Width屬性一樣):MinHeight > MaxHeight > Height > ActualHeight
- HorizontalAlignment and VerticalAlignment - 子項目相對於母容器的水平和垂直對齊(例如, Button在StackPanel中的水平或垂直對齊); HorizontalAlignment對齊的方式可分成: Left, Center, Right, Sretch(子控制項會延伸填滿母容器的配置版面空間). 而VerticalAlignment對齊方式為: Top, Center, Bottom ,Stretch; 注意:Stretch為預設值, 如果有設定Width或Height, 則以Width和Height值為優先, 下面為HorizontalAlignment 的範例說明:
<Border Background="LightBlue"
BorderBrush="Black"
BorderThickness="2"
Padding="15">
<StackPanel Background="White"
HorizontalAlignment="Center"
VerticalAlignment="Top">
<TextBlock Margin="5,0,5,30"
FontSize="20"
Foreground="Red"
VerticalAlignment="Top"
HorizontalAlignment="Center">
HorizontalAlignment Sample
</TextBlock>
<Button Background="Gold"
HorizontalAlignment="Center"
Margin="10">Left</Button>
<Button Background="LightGreen"
HorizontalAlignment="Right">Right</Button>
<Button Background="Honeydew"
HorizontalAlignment="Center">Center</Button>
<Button Background="Ivory"
HorizontalAlignment="Stretch">Stretch</Button>
</StackPanel>
</Border>
結果如圖示:
[圖1] HorizontalAlignment Sample
- Margin - 控制元素外的邊界的大小. 例如 Margin="0,10,5,25"(邊界順序為, 左, 上,右,下); 或是寫成Margin="10" 來設定成均等邊界,正確使用Margin可以精確控制項目的呈現位置.
- Padding- 控制元素邊界內的大小
首先, 我們拉出一個StackPanel, 然後塞入四個button, XAML檔和畫面如下:
<StackPanel>
<Button Name="button1"
Background="AliceBlue">Button
</Button>
<Button Name="button2"
Background="Beige">Button 2
</Button>
<Button Name="button3"
Background="Pink">Button 3
</Button>
<Button Name="button4"
Background="LightGreen">Button 4
</Button>
</StackPanel>
[圖2] 沒有Margin和Padding
然後, 我們在每個button的屬性中加入 Margin = "10", 可以看到下面的畫面中, button和其他項目有對應的邊界.
<Button Name="button1"
Background="AliceBlue"
Height="40"
Margin="10">Button
</Button>
[圖3] Margin Sample
然後, 我們再把Margin屬性換為Padding = "10", 可以看到下面的畫面, 每個button content的內邊界都作增加.
<Button Name="button1"
Background="AliceBlue"
Height="40"
Padding="10">Button
</Button>
[圖4] Padding Sample
- HorizontalContentAlignment and VerticalContentAlignment - 除了控制項可以作水平或垂直對齊外, 控制項的內容也有這樣的對齊方式, 請看下面範例和圖示.
<StackPanel>
<Button Name="button1"
Background="AliceBlue"
Height="40"
HorizontalContentAlignment="Left">Button
</Button>
<Button Name="button2"
Background="Beige"
Height="40"
HorizontalContentAlignment="Right">Button 2
</Button>
<Button Name="button3"
Background="Pink"
Height="40"
VerticalContentAlignment="Top">Button 3
</Button>
<Button Name="button4"
Background="LightGreen"
Height="40"
VerticalContentAlignment="Bottom">Button 4
</Button>
</StackPanel>
[圖5] HorizontalContentAlignment Sample
沒有留言:
張貼留言