2012-08-09 67 views
0

我希望我的应用程序在执行某些组件检查时显示正在运行的进度条。但是,由于我在桌面应用程序编程和WPF方面的知识不足,我无法找到合适的位置。何时启动WPF进度条

我试图在Window_Loaded()ContentRendered()期间显示递增的进度条,但没有运气。

而不是显示progressBar增加,它只显示进度条的最终状态。

下面是代码

public partial class Loading : Window 
{ 
    public Loading() 
    { 
     InitializeComponent(); 
     SetProgressBar(); 
     this.Show(); 
     CheckComponents(); 
    } 

    private void CheckComponents() 
    { 
     System.Threading.Thread.Sleep(3000); 

     CheckProductionDBConnection(); 
     pgrsBar.Value = 30; 

     System.Threading.Thread.Sleep(3000); 
     CheckInternalDBConnection(); 
     pgrsBar.Value = 60; 

     System.Threading.Thread.Sleep(3000); 
     CheckProductionPlanning(); 
     pgrsBar.Value = 90; 

     //MainWindow mainWindow = new MainWindow(); 
     //mainWindow.Show(); 
    } 

    private void SetProgressBar() 
    { 
     pgrsBar.Minimum = 0; 
     pgrsBar.Maximum = 100; 
     pgrsBar.Value = 0; 
    } 
//more code down here... 

我应该在哪里放置CheckComponents()方法?

回答

1

您可以将此代码放入订阅Activated事件的事件处理程序中。有一个问题是,每当窗口失去焦点后,它就会触发Activated事件。为了解决这个问题,你可以在事件处理程序中做的第一件事是取消订阅Activated事件,这样只有在第一次激活窗口时才能执行你的代码。

如果您不想延迟阻塞主线程,则还需要将此工作卸载到工作线程。如果你这样做,你将不得不调用你的电话来更新Progess栏的价值。

下面是一些示例代码,您开始:

public Loader() 
{ 
    InitializeComponent(); 
    SetProgressBar(); 

    this.Activated += OnActivatedFirstTime; 
} 

private void OnActivatedFirstTime(object sender, EventArgs e) 
{ 
    this.Activated -= this.OnActivatedFirstTime; 

    ThreadPool.QueueUserWorkItem(x => 
    { 
    System.Threading.Thread.Sleep(3000); 

    CheckProductionDBConnection(); 
    this.Dispatcher.BeginInvoke(new Action(() => pgrsBar.Value = 30)); 

    System.Threading.Thread.Sleep(3000); 
    CheckInternalDBConnection(); 
    this.Dispatcher.BeginInvoke(new Action(() => pgrsBar.Value = 60)); 

    System.Threading.Thread.Sleep(3000); 
    CheckProductionPlanning(); 
    this.Dispatcher.BeginInvoke(new Action(() => pgrsBar.Value = 90)); 
    }); 
} 

private void SetProgressBar() 
{ 
    pgrsBar.Minimum = 0; 
    pgrsBar.Maximum = 100; 
    pgrsBar.Value = 0; 
} 
+0

听起来并不像我想像的那样简单。感谢寿。我只注意到WPF与正常的窗体非常不同。 – 2012-08-09 03:13:46

+0

只是好奇又是什么?这叫什么? 'this.Dispatcher.BeginInvoke(new Action(()=> pgrsBar.Value = 90)); '这是lambda吗? – 2012-08-09 03:28:58

+0

This Works!只需将'CheckProductionDBConnection();'更改为this.Dispatcher.BeginInvoke(new Action(()=> CheckProductionDBConnection()));'以避免线程拥有错误。其他检查功能也一样。再次感谢! – 2012-08-09 03:47:44