有没有简单的方法来设置 WPF 状态栏文本?

Posted

技术标签:

【中文标题】有没有简单的方法来设置 WPF 状态栏文本?【英文标题】:Is there no simple way to set WPF StatusBar text? 【发布时间】:2010-10-21 11:36:58 【问题描述】:

我想在我的程序执行一些工作时让用户稍等片刻之前在我的状态栏中设置 TextBlock 的文本。

显然,不要像这样(不起作用)做一个漂亮的小功能:

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】:

看看这个问题: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

【讨论】:

以上是关于有没有简单的方法来设置 WPF 状态栏文本?的主要内容,如果未能解决你的问题,请参考以下文章

当前控件的工具提示中的 WPF C# 状态栏标签内容

WPF,从用户控件中更新主窗口中的状态栏

当 primaryDark 为白色时更改状态栏文本颜色

当 primaryDark 为白色时更改状态栏文本颜色

可靠的跨浏览器设置状态栏文本的方式

如何根据设置的主题更改颤动中的状态栏图标和文本颜色?