首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >WPF使用Dipatcher强制GUI更新

WPF使用Dipatcher强制GUI更新
EN

Stack Overflow用户
提问于 2010-09-24 17:11:04
回答 1查看 1K关注 0票数 0

我只需要显示一个自定义控件(带旋转指针的时钟),并用它替换鼠标光标,问题是如果我写:

代码语言:javascript
复制
Me.gridScreen.Visibility = Visibility.Visible
' some operations that takes about 1 second
Me.gridScreen.Visibility = Visibility.Hidden
(gridScreen is the grid that contains the user-control)

显然,我什么也看不到,因为UI的更新发生在过程的末尾。我尝试过Me.UpdateLayout(),但它不起作用。

我已经尝试了很多方法来使用拆解器,但都没有成功:-(

这是我失败的尝试:

(uCurClock是用户控件,gridScreen是一个放置在窗口顶层的网格,具有透明的背景,包含用户控件)

代码语言:javascript
复制
Private Sub showClock()
    Dim thread = New System.Threading.Thread(AddressOf showClockIntermediate)
    thread.Start()
End Sub

Private Sub hideClock()
    Dim thread = New System.Threading.Thread(AddressOf hideClockIntermediate)
    thread.Start()
End Sub

Private Sub showClockIntermediate()
    Me.Dispatcher.BeginInvoke(DispatcherPriority.Normal, _
        New Action(AddressOf showClockFinale))
End Sub

Private Sub hideClockIntermediate()
    Me.Dispatcher.BeginInvoke(DispatcherPriority.Normal, _
        New Action(AddressOf hideClockFinale))
End Sub

Private Sub showClockFinale()
    Dim pt As Point = Mouse.GetPosition(Nothing)
    Me.uCurClock.Margin = New Thickness(pt.X - 9, pt.Y - 9, 0, 0)
    Me.gridScreen.Visibility = Visibility.Visible
    Me.Cursor = Cursors.None
    Me.UpdateLayout()
End Sub

Private Sub hideClockFinale()
    Me.gridScreen.Visibility = Visibility.Hidden
    Me.Cursor = Cursors.Arrow
    Me.UpdateLayout()
End Sub

Private Sub u_MouseMove(ByVal sender As System.Object, _
    ByVal e As MouseEventArgs) Handles gridScreen.MouseMove

    Dim pt As Point = e.GetPosition(Nothing)
    Me.uCurClock.Margin = New Thickness(pt.X - 9, pt.Y - 9, 0, 0)

    e.Handled = True
End Sub

Private Sub u_MouseEnter(ByVal sender As System.Object, _
    ByVal e As MouseEventArgs) Handles gridScreen.MouseEnter

    Me.uCurClock.Visibility = Visibility.Visible

    e.Handled = True
End Sub

Private Sub u_MouseLeave(ByVal sender As System.Object, _
    ByVal e As MouseEventArgs) Handles gridScreen.MouseLeave

    Me.uCurClock.Visibility = Visibility.Hidden

    e.Handled = True
End Sub

PIleggi

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2010-09-24 17:55:36

问题不在于在dispatcher上执行的消息的组成,而在于您在dispatcher上执行的是长期运行的工作。您必须确保在后台线程上执行长时间运行/可能阻塞的操作。最简单的方法是使用BackgroundWorker组件。

请原谅C#:

代码语言:javascript
复制
var backgroundWorker = new BackgroundWorker();

backgroundWorker.DoWork += delegate
{
    // long running work goes here
};
backgroundWorker.RunWorkerCompleted += delegate
{
    // change cursor back to normal here
};

// change cursor to busy here

// kick off the background task
backgroundWorker.RunWorkerAsync();
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3785641

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档