WPF VB 在别的线程里改UI

新手上路,请多包涵

我利用了一个Timer来扫描Xbox 360控制器的按键
但是不知道怎么改动UI
错误信息:

An exception of type 'System.InvalidOperationException' occurred in WindowsBase.dll but was not handled in user code
Additional information: The calling thread cannot access this object because a different thread owns it.


Imports Microsoft.Xna.Framework
Imports Microsoft.Xna.Framework.Input
Imports System.Timers
Imports System.Windows.Threading

Public Class XboxControllerStatus
    Friend WithEvents Timer1 As Timer
    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs)                 Handles Timer1.Elapsed

        Dim currentState As GamePadState = GamePad.GetState(PlayerIndex.One)
        If currentState.IsConnected Then
            If currentState.Buttons.LeftShoulder.Pressed Then
                LB.Content = "Pressed"

            Else
                LB.Content = "LB"
            End If
        End If

    End Sub

End Class
阅读 3.2k
2 个回答

跨线程修改UI线程需要使用UI线程的Dispatcher.BeginInvoke或Invoke方法。

新手上路,请多包涵

看来碰vb的真的很少.我给你答案吧.
Imports System.Threading

Class MainWindow

Dim Thread0 As Thread
Private Sub Button_Click(sender As Object, e As RoutedEventArgs)
    Thread0 = New Thread(AddressOf Thread_0)
    Thread0.Start()

End Sub
Private Sub Thread_0()
    Dim i As Integer = 2

    Dispatcher.BeginInvoke(New UpdateLabelDelegate(AddressOf UpUI), i, "testtext")
End Sub


Private Delegate Sub UpdateLabelDelegate(ByVal i As Integer, ByVal s As String)

Private Sub UpUI(ByVal i As Integer, ByVal s As String)
    Select Case i
        Case 0
        Case 1
            textbox1.Text = s
        Case 2
            TextBlock1.Text = s
    End Select
End Sub

End Class