摘要:WPF學習日誌 ~ StackPanel ~
前面我們測試過幾篇有關WPF的應用程式,不知道有沒有發現,我們沒有辦法指定兩個以上的東西(物件)給Content屬性,WIndow的 COntent、Button的Content等等,那怎麼辦呢?總不能用來用去都是使用一個東東而已吧..所以接下來我們要測試一些有關"容器"的部 分,在WPF中有下面幾種容器
,這篇只會提到StackPanel的部分,有興趣的朋友可以先自行測試看看,或是到MSDN去看看相關細節;好,下面來看看測試的程式碼吧
- Dim sp As StackPanel
- Dim rnd As Random
- Private Sub Window1_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded
- rnd = New Random()
- sp = New StackPanel
- sp.Background = Brushes.AliceBlue
- Me.Content = sp
- For i As Integer = 1 To 9
- Dim btn = New Button
- btn.Name = "Button" & i
- btn.FontFamily = New FontFamily("Consola")
- Randomize()
- btn.FontSize = rnd.Next(10, 25)
- ''用 "_" 設定當按下"alt"按鍵時出現的"快速鍵提示字"
- btn.Content = "Button No._" & i
- ''設定按鈕間的間隔
- btn.Margin = New Thickness(5)
- ''可以將下面兩行程式碼註解看看不同的地方
- btn.HorizontalAlignment = Windows.HorizontalAlignment.Center
- btn.VerticalAlignment = Windows.VerticalAlignment.Center
- AddHandler btn.Click, AddressOf Button_Click
- sp.Children.Add(btn)
- Next
- Me.SizeToContent = Windows.SizeToContent.WidthAndHeight
- ''將下面程式碼註解掉並改變視窗大小,看看結果有何不同
- Me.ResizeMode = Windows.ResizeMode.CanMinimize
- End Sub
- Private Sub Button_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
- MessageBox.Show(CType(sender, Button).Name)
- If sp.Orientation = Orientation.Horizontal Then
- sp.Orientation = Orientation.Vertical
- Else
- sp.Orientation = Orientation.Horizontal
- End If
- End Sub
Dim sp As StackPanel
Dim rnd As Random
Private Sub Window1_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded
rnd = New Random()
sp = New StackPanel
sp.Background = Brushes.AliceBlue
Me.Content = sp
For i As Integer = 1 To 9
Dim btn = New Button
btn.Name = "Button" & i
btn.FontFamily = New FontFamily("Consola")
Randomize()
btn.FontSize = rnd.Next(10, 25)
''用 "_" 設定當按下"alt"按鍵時出現的"快速鍵提示字"
btn.Content = "Button No._" & i
''設定按鈕間的間隔
btn.Margin = New Thickness(5)
''可以將下面兩行程式碼註解看看不同的地方
btn.HorizontalAlignment = Windows.HorizontalAlignment.Center
btn.VerticalAlignment = Windows.VerticalAlignment.Center
AddHandler btn.Click, AddressOf Button_Click
sp.Children.Add(btn)
Next
Me.SizeToContent = Windows.SizeToContent.WidthAndHeight
''將下面程式碼註解掉並改變視窗大小,看看結果有何不同
Me.ResizeMode = Windows.ResizeMode.CanMinimize
End Sub
Private Sub Button_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
MessageBox.Show(CType(sender, Button).Name)
If sp.Orientation = Orientation.Horizontal Then
sp.Orientation = Orientation.Vertical
Else
sp.Orientation = Orientation.Horizontal
End If
End Sub
程式執行之後可以看到StackPanel是以水平或是垂直的方向來排列控制項,這就是這個容器的特性了,其 中我們在設定Button的屬性時有用到底線( _ ),程式執行的時候按下"alt"按鍵,你可以看到數字鍵的下面都出現了底線,按下"alt+1",就可以直接觸發Button1的Click事件了。