1

我有一个 WPF 应用程序,单击按钮后,该应用程序会进入一个可能需要 4-10 秒的计算。我想在该操作期间更新背景的不透明度并显示进度条。

为此,我使用以下代码:

this.Cursor = System.Windows.Input.Cursors.Wait;

// grey-out the main window
SolidColorBrush brush1 = new SolidColorBrush(Colors.Black);
brush1.Opacity = 0.65;
b1 = LogicalTreeHelper.FindLogicalNode(this, "border1") as Border;
b1.Opacity = 0.7;
b1.Background = brush1;

// long running computation happens here .... 
// show a modal dialog to confirm results here
// restore background and opacity here. 

当我运行代码时,在模态对话框出现之前,背景和不透明度不会改变。在计算开始之前,我怎样才能让这些视觉变化立即发生我记得,在 Windows 窗体中,每个控件都有一个 Update() 方法,根据需要执行此操作。什么是 WPF 模拟?

4

2 回答 2

1

如果您要在后台线程中进行长时间运行的计算怎么办?完成后将结果分派回 UI 线程...

老实说,我怀疑那里没有其他东西可以解决您的问题。也许嵌套抽水可以解决问题,但我真的很怀疑。

以防万一此参考有用:使用 Dispatcher 构建更具响应性的应用程序

于 2010-02-26T15:14:42.453 回答
0

使用 DoEvents() 代码,如下所示:http:
//blogs.microsoft.co.il/blogs/tamir/archive/2007/08/21/How-to-DoEvents-in-WPF_3F00_.aspx

我的实际代码:

private void GreyOverlay()
{
    // make the overlay window visible - the effect is to grey out the display
    if (_greyOverlay == null)
        _greyOverlay = LogicalTreeHelper.FindLogicalNode(this, "overlay") as System.Windows.Shapes.Rectangle;
    if (_greyOverlay != null)
    {
        _greyOverlay.Visibility = Visibility.Visible;
        DoEvents();
    }
}

private void DoEvents()
{
    // Allow UI to Update...
    DispatcherFrame f = new DispatcherFrame();
    Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background,
                                             new Action<object>((arg)=> {
                                                     DispatcherFrame fr = arg as DispatcherFrame;
                                                     fr.Continue= false;
                                                 }), f);
    Dispatcher.PushFrame(f);
}
于 2010-02-26T18:10:50.630 回答