WPF學習日誌 ~ Grid ~
Grid這個"容器"相較之前的容器來看,顯的比較複雜一些,需要設定的東西比較多,下面用簡單的程式碼展示一下基本的功能,希望大家對於Grid能有一些基本的了解
Dim gd As Grid
Private Sub Window1_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded
gd = New Grid
Me.Title = "Grid Test"
''設定Form的大小跟Content的長、寬是一樣的
Me.SizeToContent = Windows.SizeToContent.WidthAndHeight
Me.Content = gd
''為了方面觀看變化,我們把隔線設定為顯示
gd.ShowGridLines = True
''為了範例需要我們把新增欄、列的新增跟按鈕的新增分開處理
For iRow As Integer = 0 To 4
''新增Grid的列
Dim rd = New RowDefinition
If iRow = 4 Then
''最後一列為了展示跨越欄位的button,這邊做特殊設定
''可以自行修改看看GridUnitType的部分看看有什麼不同
rd.Height = New GridLength(100, GridUnitType.Star)
Else
rd.Height = GridLength.Auto
End If
gd.RowDefinitions.Add(rd)
Next
For iCol As Integer = 0 To 4
''新增Grid的欄
Dim cd As New ColumnDefinition
If iCol = 4 Then
cd.Width = New GridLength(100, GridUnitType.Star)
Else
cd.Width = GridLength.Auto
End If
gd.ColumnDefinitions.Add(cd)
Next
For z As Integer = 0 To 3
For x As Integer = 0 To 3
Dim btn As New Button
btn.Name = "Button" & z & "_" & x
btn.Content = "Button " & z & "-" & x
btn.Margin = New Thickness(2)
Grid.SetColumn(btn, x)
Grid.SetRow(btn, z)
gd.Children.Add(btn)
Next
Next
Dim btnBig As New Button
btnBig.Name = "btnBig"
btnBig.Content = "Big Button"
btnBig.Margin = New Thickness(2)
Grid.SetRow(btnBig, 4)
Grid.SetColumn(btnBig, 0)
''設定跨越Grid的三格,如果是跨越Row的話是用SetRowSpan
Grid.SetColumnSpan(btnBig, 3)
gd.Children.Add(btnBig)
End Sub
留言