由于您没有显示完整的
BackgroundWorker代码,所以我无法确定您是否正确实现了它。这样,我所能做的就是向您展示一个更新
ProgressBar控件的简单工作示例:
UserControlXAML:
<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>
MainWindowXAML:
<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 } }}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)