我在从ListView读取项目时遇到问题。 ListView在主线程中,我读出它的部分是在另一个类和另一个线程中。我的代码如下:
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim ltm As ListViewItem = New ListViewItem
ltm.Text = "test1"
ltm.SubItems.Add("test2")
ltm.SubItems.Add("test3")
Me.ListView2.Items.Add(ltm)
Dim l As New test
Dim x As New Threading.Thread(AddressOf l.readout)
End Sub
End Class
Public Class test
Public Sub readout()
For Each i As ListViewItem In Form1.ListView2.Items
Dim command As String = i.SubItems(0).Text
Dim value As String = i.SubItems(1).Text
Dim executeon As String = i.SubItems(2).Text
MsgBox(command & vbCrLf & value & vbCrLf & executeon)
Next
End Sub
End Class
我听说过调用并找到了一些示例代码。我也尝试了以下内容:
Dim selectedItem = CStr((New Func(Of String)(Function() Form1.ListView2.Items(0).Text)).Invoke)
MsgBox(selectedItem)
然而,这也不起作用。没有错误消息,它只是没有显示任何消息框。当我删除线程和同一个类时,它工作得很好。有谁知道为什么它不起作用?
答案 0 :(得分:0)
基本上,您无法从另一个线程触摸UI线程。很难确切地告诉你要做什么,但你当然可以检查你是否在非UI线程上并使用InvokeRequired和BeginInvoke在UI线程上继续执行。
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim ltm As ListViewItem = New ListViewItem
ltm.Text = "test1"
ltm.SubItems.Add("test2")
ltm.SubItems.Add("test3")
Me.ListView2.Items.Add(ltm)
Dim l As New test(ListView2)
Dim x As New Threading.Thread(AddressOf l.readout)
x.Start()
End Sub
End Class
Public Class test
Public Sub New(listview As ListView)
_listview = listview
End Sub
Private _listview As ListView
Public Sub readout()
If _listview.InvokeRequired Then
_listview.BeginInvoke(New Action(AddressOf readout))
Else
For Each i As ListViewItem In Form1.ListView2.Items
Dim command As String = i.SubItems(0).Text
Dim value As String = i.SubItems(1).Text
Dim executeon As String = i.SubItems(2).Text
MsgBox(command & vbCrLf & value & vbCrLf & executeon)
Next
End If
End Sub
End Class