有没有简单的方法来设置WPF StatusBar文本?

时间:2009-04-23 21:42:09

标签: .net wpf multithreading backgroundworker statusbar

我希望在我的程序执行一些工作之前让用户等待片刻之前,在我的StatusBar中设置TextBlock的Text。

显然,不是像这样做一个很好的小功能(不起作用):

Function Load(ByVal Id As Guid) As Thing
    Cursor = Cursors.Wait
    TextBlockStatus.Text = "Loading..."
    TextBlockStatus.UpdateLayout()
    Dim Found = From t In db.Thing _
                Where t.Id = Id _
                Select t
    TextBlockStatus.Text = String.Empty
    Cursor = Cursors.Arrow
    Return Found
End Function

我必须使用这种怪物:

Private WithEvents LoadWorker As BackgroundWorker

Private Sub Window1_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded
    InitializeLoadWorker()
End Sub

Private Sub InitializeLoadWorker()
    LoadWorker = New BackgroundWorker
    LoadWorker.WorkerSupportsCancellation = False
    LoadWorker.WorkerReportsProgress = False
    AddHandler LoadWorker.DoWork, AddressOf LoadBackgroundWorker_DoWork
    AddHandler LoadWorker.RunWorkerCompleted, AddressOf LoadBackgroundWorker_RunWorkerCompleted
End Sub

Sub Load(ByVal Id As Guid)
    Cursor = Cursors.Wait
    LoadWorker.RunWorkerAsync(Argument)
End Sub

Private Sub LoadBackgroundWorker_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs)
    Dim Worker As BackgroundWorker = DirectCast(sender, BackgroundWorker)
    Dim Id As Guid = DirectCast(e.Argument, Guid)
    e.Result = From t In db.Thing _
               Where t.Id = Id _
               Select t
End Sub

Private Sub LoadBackgroundWorker_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs)
    TextBlockStatus.Text = String.Empty
    Cursor = Cursors.Arrow
    Dim Found As Thing = DirectCast(e.Result, Thing)
    'now do something with the found thing here instead of where Load() is called.'
End Sub

Load()函数现在是Sub !!

必须有更好的方法来处理这种简单的情况。这不需要是异步的。

1 个答案:

答案 0 :(得分:1)

看一下这个问题:Display Wait Screen in WPF

接受的答案有一种方法可以做我想你想要的,没有后台工人类。

从答案中的链接到另一个问题,这可能适用于VB.NET(我还没试过)

Public Sub AllowUIToUpdate()

    Dim frame As New DispatcherFrame()

    Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Render, New DispatcherOperationCallback(AddressOf JunkMethod), frame)

    Dispatcher.PushFrame(frame)

End Sub

Private Function JunkMethod(ByVal arg As Object) As Object

    DirectCast(arg, DispatcherFrame).Continue = False
    Return Nothing

End Function