我正在创建一个在 VB.NET 中使用 TreeListView 的简单示例(或至少一个我可以遵循的示例),但我遇到了一个问题。当我运行下面的代码时,最初一切正常。我有一棵带有宠物名字分支的宠物主人树。但是在我展开其中一个节点并移动鼠标后,我收到一条错误消息,告诉我无法将字符串对象转换为 petowner 对象(我的对象类)。我明白这意味着什么,但 VS 并没有告诉我错误在哪里,我也不能将它困在 try-catch 中。我正在寻找一些见解。
另外:谁能告诉我我从 C# 到 VB 的转换是否正确;特别是 lambda 函数代替 ChildrenGetter 和 AspectGetter 方法中的委托?我相当肯定这就是错误所在。
提前致谢。
Public Class Form1
Public Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
Dim PetOwners As New List(Of PetOwner)
Dim PetOwner As PetOwner
PetOwner = New PetOwner
PetOwner.OwnerName = "Steve"
PetOwner.PetNames.Add("Bob the Cat")
PetOwner.PetNames.Add("Snoop the Dog")
PetOwners.Add(PetOwner)
PetOwner = New PetOwner
PetOwner.OwnerName = "Ann"
PetOwners.Add(PetOwner)
PetOwner = New PetOwner
PetOwner.OwnerName = "Joe"
PetOwner.PetNames.Add("Shoeless")
PetOwners.Add(PetOwner)
Try
tlvPetOwners.CanExpandGetter = Function(po As PetOwner) po.PetNames.Count > 0
tlvPetOwners.ChildrenGetter = Function(po As Object)
Dim RetVal As Object = Nothing
Try
If TypeOf po Is PetOwner Then
RetVal = CType(po, PetOwner).PetNames
Else
RetVal = po
End If
Catch ex As Exception
Debug.Print(ex.ToString)
Finally
End Try
Return RetVal
End Function
Dim OwnerColumn As New OLVColumn()
OwnerColumn.AspectGetter = Function(po As Object)
Dim RetVal As Object = Nothing
Try
If TypeOf po Is PetOwner Then
RetVal = CType(po, PetOwner).OwnerName
Else
RetVal = po
End If
Catch ex As Exception
Debug.Print(ex.ToString)
Finally
End Try
Return RetVal
End Function
tlvPetOwners.Columns.Add(OwnerColumn)
tlvPetOwners.Roots = PetOwners
Catch ex As Exception
Debug.Print(ex.ToString)
End Try
End Sub
End Class
Public Class PetOwner
Public OwnerName As String
Public PetNames As New List(Of String)
End Class