如何使用ProgressBar更新正确实现BackgroundWorker?

如何使用ProgressBar更新正确实现BackgroundWorker?,第1张

如何使用ProgressBar更新正确实现BackgroundWorker?

由于您没有显示完整的

BackgroundWorker
代码,所以我无法确定您是否正确实现了它。这样,我所能做的就是向您展示一个更新
ProgressBar
控件的简单工作示例

UserControl
XAML:

<UserControl x:Class="WpfApplication1.Views.TestView"    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"     xmlns:d="http://schemas.microsoft.com/expression/blend/2008"     mc:Ignorable="d"     d:DesignHeight="300" d:DesignWidth="300" Loaded="UserControl_Loaded">    <ProgressBar x:Name="progressBar" Height="25" Margin="20" Minimum="0"         Maximum="50" /></UserControl>

MainWindow
XAML:

<Window x:Class="WpfApplication1.MainWindow"    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"    xmlns:Views="clr-namespace:WpfApplication1.Views"    title="MainWindow" Height="350" Width="525">    <Views:TestView /></Window>

UserControl
后面的代码:

using System.ComponentModel;using System.Threading;using System.Windows;using System.Windows.Controls;namespace WpfApplication1.Views{    public partial class TestView : UserControl    {        private BackgroundWorker backgroundWorker = new BackgroundWorker();        public TestView()        { InitializeComponent(); backgroundWorker.WorkerReportsProgress = true; backgroundWorker.ProgressChanged += ProgressChanged; backgroundWorker.DoWork += DoWork; // not required for this question, but is a helpful event to handle backgroundWorker.RunWorkerCompleted += BackgroundWorker_RunWorkerCompleted;        }        private void UserControl_Loaded(object sender, RoutedEventArgs e)        { backgroundWorker.RunWorkerAsync();        }        private void DoWork(object sender, DoWorkEventArgs e)        { for (int i = 0; i <= 100; i++) {     // Simulate long running work     Thread.Sleep(100);     backgroundWorker.ReportProgress(i); }        }        private void ProgressChanged(object sender, ProgressChangedEventArgs e)        { // This is called on the UI thread when ReportProgress method is called progressBar.Value = e.ProgressPercentage;        }        private void BackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)        { // This is called on the UI thread when the DoWork method completes // so it's a good place to hide busy indicators, or put clean up pre        }    }}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5018437.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-15
下一篇 2022-11-15

发表评论

登录后才能评论

评论列表(0条)

保存