成員名稱 |
說明 |
|
此爲默認值,表示TreeView控件將由操作系統來繪製。 |
OwnerDrawAll |
此表示TreeView控件之節點的所有項目都將由您自行繪製,包括:圖示、複選框、加號、減號、以及連接節點的線條。 |
OwnerDrawText |
此表示TreeView控件之節點的卷標部分將由您自行繪製,至於節點的其它項目則由操作系統來繪製,包括:圖示、複選框、加號、減號、以及連接節點的線條。 |
Private tagFont As New Font("標楷體", 9, _
FontStyle.Bold Or FontStyle.Italic Or FontStyle.Underline)
While drProduct.Read()
' 以產品名稱作爲根節點。
rootNode = New TreeNode(drProduct(0).ToString)
TreeView1.Nodes.Add(rootNode)
' 以其它字段的內容作爲子節點。
For i As Integer = 1 To nFieldCount – 1
childNode = New TreeNode( _
drProduct.GetName(i) & ":" & drProduct(i).ToString)
TreeView1.Nodes(nRow).Nodes.Add(childNode)
' 如果庫存量低於安全庫存,則將警示訊息儲
' 存於節點的Tag屬性中。
If drProduct.GetSqlInt16(3) < drProduct.GetSqlInt16(4) Then
TreeView1.Nodes(nRow).Nodes(0).Tag = _
"低於安全庫存,請儘快補貨。"
End If
Next
nRow += 1
End While
TreeView1.DrawMode = TreeViewDrawMode.OwnerDrawText
Private Sub TreeView1_DrawNode(ByVal sender As Object, _
ByVal e As DrawTreeNodeEventArgs) Handles TreeView1.DrawNode
' 繪製被選取之節點的背景色與節點文字。
If (e.State And TreeNodeStates.Selected) <> 0 Then
' 繪製被選取之節點的背景色。如果該節點擁有標記文字
' 「低於安全庫存,請儘快補貨。」的話,NodeBounds方法
' 會使得醒目提示區域擁有足夠的大小來容納它。
e.Graphics.FillRectangle(Brushes.Green, NodeBounds(e.Node))
' 提取節點字型。如果節點字型未被設定,
' 就使用TreeView的字型。
Dim nodeFont As Font = e.Node.NodeFont
If nodeFont Is Nothing Then
nodeFont = CType(sender, TreeView).Font
End If
' 繪製節點文字。
e.Graphics.DrawString(e.Node.Text, nodeFont, _
Brushes.White, e.Bounds.Left - 2, e.Bounds.Top)
Else
e.DrawDefault = True
End If
' 如果存在節點標記,就將它繪製在節點標籤的右側。
If (e.Node.Tag IsNot Nothing) Then
e.Graphics.DrawString(e.Node.Tag.ToString(), tagFont, _
Brushes.Yellow, e.Bounds.Right + 2, e.Bounds.Top)
End If
' 如果節點擁有焦點,便將焦點矩形繪製得夠大
' 以便能夠容納節點卷標文字。
If (e.State And TreeNodeStates.Focused) <> 0 Then
Using focusPen As New Pen(Color.Black)
focusPen.DashStyle = _
System.Drawing.Drawing2D.DashStyle.Dot
Dim focusBounds As Rectangle = NodeBounds(e.Node)
focusBounds.Size = New Size(focusBounds.Width - 1, _
focusBounds.Height - 1)
e.Graphics.DrawRectangle(focusPen, focusBounds)
End Using
End If
End Sub
' 不論用戶按一下節點卷標或節點標記都選取該節點。
Private Sub TreeView1_MouseDown(ByVal sender As Object, _
ByVal e As MouseEventArgs) Handles TreeView1.MouseDown
Dim clickedNode As TreeNode = TreeView1.GetNodeAt(e.X, e.Y)
If NodeBounds(clickedNode).Contains(e.X, e.Y) Then
TreeView1.SelectedNode = clickedNode
End If
End Sub
Private Function NodeBounds(ByVal node As TreeNode) As Rectangle
' 將傳回值設定成正常的節點邊界範圍。
Dim bounds As Rectangle = node.Bounds
If (node.Tag IsNot Nothing) Then
' 取得TreeView控件的Graphics對象並使用
' 它來計算節點標記的顯示寬度。
Dim g As Graphics = TreeView1.CreateGraphics()
Dim tagWidth As Integer = CInt(g.MeasureString( _
node.Tag.ToString(), tagFont).Width) + 6
' 使用計算所得的值來調整節點邊界範圍。
bounds.Offset(tagWidth \ 2, 0)
bounds = Rectangle.Inflate(bounds, tagWidth \ 2, 0)
End If
Return bounds
End Function