WPF进度条
在我的WPF应用程序中,我必须在计时器刻度事件中显示进度条进度,我写的如下,
System.Windows.Forms.Timer timer; public MainWindow() { timer = new System.Windows.Forms.Timer(); timer.Interval = 1000; this.timer.Tick += new System.EventHandler(this.timer_Tick); }
加载事件如下
private void Window_Loaded(object sender, RoutedEventArgs e) { progressBar1.Minimum = 0; progressBar1.Value = DateTime.Now.Second; progressBar1.Maximum = 700; timer.Start(); }
最后在tick事件中,
private void timer_Tick(object sender, EventArgs e) { Duration duration = new Duration(TimeSpan.FromSeconds(20)); //progress bar animation System.Windows.Media.Animation.DoubleAnimation doubleanimation = new System.Windows.Media.Animation.DoubleAnimation(200.0, duration); progressBar1.BeginAnimation(ProgressBar.ValueProperty, doubleanimation); }
当我执行我的程序时,进度条显示两三个条的进度,然后它停止递增。 后来对进展没有任何影响。 我的代码出了什么问题。 请帮忙!..
关心Sangeetha
在我的WPF应用程序中,我有…
System.Windows.Forms.Timer timer;
这是错误的计时器类型。 请改用DispatcherTimer 。
当我执行我的程序时,进度条显示两三个条的进度然后停止
这让我感到惊讶,我根本没想到它会起作用。 这意味着你也可能遇到其他问题,比如阻塞主(调度程序)线程。
您只在Loaded事件中设置Value一次:
progressBar1.Value = DateTime.Now.Second;
Tick事件中的progressBar1.Value
没有变化。 所以它认为它停止了移动。
由于ProgressBar
与任何特定行为无关,因此它看起来像是一个不确定栏的作业。
这个其他的SO问题提供了一些有关它的见解。 简而言之,它是一个XAML单线程:
然后在代码中,你这样做:
progressBar1.IsIndeterminate = true; // start animation progressBar1.IsIndeterminate = false; // stop animation
使用DispatcherTimer而不是Timer(Forms对象),并使用ProgressBar的Value属性。
试试这个 :
MainWindows.xaml:
MainWindows.xaml.cs:
using System.Windows; using System.Windows.Threading; namespace WpfApplication1 { public partial class MainWindow : Window { private DispatcherTimer timer; public MainWindow() { InitializeComponent(); this.timer = new DispatcherTimer(); this.timer.Tick += timer_Tick; this.timer.Interval = new System.TimeSpan(0, 0, 1); this.timer.Start(); } private void timer_Tick(object sender, System.EventArgs e) { this.pb.Value = System.DateTime.Now.Second % 100; } } }
您可以通过更改Value属性来更改进度条的行为(不要忘记xaml中的Maximum属性定义)。
我发现这个( WPFmultithreading:使用BackgroundWorker和报告UI的进度。链接 )包含一个很好的解决方案来满足我的需求,尽管有一个对话框。
我发现非常有用的一件事是工作线程无法访问MainWindow的控件(在它自己的方法中),但是当在主窗口事件处理程序中使用委托时,它是可能的。
worker.RunWorkerCompleted += delegate(object s, RunWorkerCompletedEventArgs args) { pd.Close(); // Get a result from the asynchronous worker T t = (t)args.Result this.ExampleControl.Text = t.BlaBla; };