共享 WPF 控件

Make WPF-control shared

我正在尝试在后台线程中借助 MainWindow Class 的 Public 共享子从另一个 class 的方法 运行 访问标签,例如这个:

    Private Delegate Sub ProgressReportInvoker(ByVal progressStr As String)

    Public Shared Sub ProgressReport(ByVal progressStr As String)
        If MainWindow.Label.Dispatcher.CheckAccess() Then
            MainWindow.Label.Content = progressStr
        Else
            MainWindow.Label.Dispatcher.Invoke(
                            New ProgressReportInvoker(AddressOf ProgressReport),
                            progressStr)
        End If
    End Sub

来自另一个 class 的电话如下:

MainWindow.ProgressReport("Sample text") 

但是我在 "MainWindow.Label" 上有这个错误:

Reference to a non-shared member requires an object reference.

我注意到,如果我将 MainWindow.g.i.vb 中的标签声明为 Public 共享,那么错误就消失了:

#ExternalSource ("..\..\MainWindow.xaml", 11)
    <System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")>
    Public Shared WithEvents Label As System.Windows.Controls.Label

#End ExternalSource

但是这个文件是从 *.XAML 文件中自动生成的,所以在我编译代码时需要先查看一下。

是否有任何方法可以在 *.XAML 文件中共享控制权,或者是否有任何其他方法可以使我的任务成为可能?

您应该访问 MainWindow 的实例而不是类型本身:

Public Shared Sub ProgressReport(ByVal progressStr As String)
    Dim mainWindow = Application.Current.Windows.OfType(Of MainWindow).FirstOrDefault()
    If mainWindow.Label.Dispatcher.CheckAccess() Then
        mainWindow.Label.Content = progressStr
    Else
        mainWindow.Label.Dispatcher.Invoke(
                            New ProgressReportInvoker(AddressOf ProgressReport),
                            progressStr)
    End If
End Sub

I tried this before but problem is in multitasking. I can't access the form from another thread without some special moves which I don't know about

您只能在最初创建它的线程中访问 UI 控件:

Application.Current.Dispatcher.BeginInvoke(New Action(Sub()
                                                          Dim mainWindow = Application.Current.Windows.OfType(Of MainWindow).FirstOrDefault()
                                                          mainWindow.Label.Content = progressStr
                                                      End Sub))

使用任何全局的东西都是非常糟糕的做法 (shared/static)。使用 class 实例或其他机制(依赖注入、消息传递、事件等)在独立的 class 之间进行通信。