如何在 WPF 中设置 ProgressBar 的可见性? [英] How to set the visibility of a ProgessBar in WPF?

查看:88
本文介绍了如何在 WPF 中设置 ProgressBar 的可见性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近才开始使用 WPF 并且正在尝试实现一个 ProgressBar,但无法让它做我想做的事情.

I just recently began working with WPF and am trying to implement a ProgressBar but can't get it to do what I want.

我想要的只是让 UI 在任务发生时显示进度条,否则它不应该是可见的.

All I want is for the UI to show the progress bar while a task is occurring, but it should not be visible otherwise.

这是我在 xaml 中的内容:

This what I have in the xaml:

<ProgressBar x:Name="pbarTesting" HorizontalAlignment="Left" Height="37"
    Margin="384,301,0,0" VerticalAlignment="Top" Width="264" IsHitTestVisible="True"
    IsIndeterminate="True" Visibility="Collapsed"/>

在我写的应用程序中:

progressBar.Visibility = Visibility.Visible;
doTimeConsumingStuff();
progressBar.Visibility = Visibility.Hidden;

但是,当我处理耗时的事情时,进度条永远不会出现.谁能告诉我我做错了什么?

However, when I get to the time consuming stuff, the progress bar never shows up. Can anyone tell me what I'm doing wrong?

推荐答案

WPF 开始时只有一个线程,称为 UI 线程.除了 UI 线程之外,UI 不会更新.当我们在 UI 线程中进行长时间运行的操作时;UI 更新停止.因此,当我们需要在长时间运行的操作中更新 UI 时,我们可以在 UI 线程以外的其他线程中启动长时间运行的操作.

WPF starts with only one thread which is called UI thread. UI doesn't update other than UI thread. When we do a long running operation in UI thread; Update of UI halts. So, when we need to update UI during a long running operation, we can start the long running operation in other thread than UI thread.

在以下示例中,我在后台线程中启动了一个长时间运行的操作.操作完成后,它返回一个值,我将其放入 UI 线程中.

In the following example I started a long running operation in a backgroud thread. When operation finish it returns a value and I took it in UI thread.

private void MethodThatWillCallComObject()
        {
            System.Threading.Tasks.Task.Factory.StartNew(() =>
            {
                //this will call in background thread
                return this.MethodThatTakesTimeToReturn();
            }).ContinueWith(t =>
            {
                //t.Result is the return value and MessageBox will show in ui thread
                MessageBox.Show(t.Result);
            }, System.Threading.Tasks.TaskScheduler.FromCurrentSynchronizationContext());
        }

        private string MethodThatTakesTimeToReturn()
        {
            System.Threading.Thread.Sleep(5000);
            return "end of 5 seconds";
        }

这篇关于如何在 WPF 中设置 ProgressBar 的可见性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆