VB.NET委托函数返回布尔值

时间:2014-11-02 15:20:56

标签: vb.net delegates

我使用的是BackgroundWorker,我需要使用委托函数来查看是否检查了ListViewItem,但我一直收到跨线程错误。这一定是我写作的方式。有什么帮助吗?

    Dim delListViewItemChecked As ListViewItemCheckedDelegate = AddressOf ListViewItemChecked
    delListViewItemChecked.Invoke(ListViewPhotos, 0)

Private Delegate Function ListViewItemCheckedDelegate(ByVal listView As ListView, ByVal index As Integer) As Boolean

Private Function ListViewItemChecked(ByVal listView As ListView, ByVal index As Integer) As Boolean
    If listView.Items(index).Checked = True Then
        Return True
    Else
        Return False
    End If
End Function

1 个答案:

答案 0 :(得分:0)

试试这个:

  1. 不要将listView作为参数传递给ListViewItemCheckedDelegate。
  2. 在后台工作程序的DoWork处理程序中声明一个新的委托实例。
  3. 此示例似乎正常工作:

    Private Delegate Function ListViewItemCheckedDelegate(ByVal index As Integer) As Boolean
    
    Private Function ListViewItemChecked(ByVal index As Integer) As Boolean
    Return ListView1.Visible
    End Function
    
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    bkg1.RunWorkerAsync()
    End Sub
    
    Private Sub bkg1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bkg1.DoWork
    Dim delListViewItemChecked As New ListViewItemCheckedDelegate(AddressOf ListViewItemChecked)
    MsgBox(Me.Invoke(delListViewItemChecked, 3)) ' arbitrary 3
    End Sub