如何根据进度百分比更改标签内容

时间:2016-02-02 04:54:08

标签: c#

在我的项目中,我只是将一些文件从源复制到目标。在复制文件期间,我增加了进度值。现在,我想添加一个标签内容,即在复制过程中“复制”,然后在完成文件复制后“完成”。我的代码没有用。

      <StackPanel>
            <StackPanel.Resources>
                <Style TargetType="Label">
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding ProgressPercentage}" Value="0">
                            <Setter Property="Visibility" Value="Hidden"/>
                        </DataTrigger>
                        <DataTrigger Binding="{Binding ProgressPercentage}" Value="100">
                            <Setter Property="Content" Value="Completed"/>
                        </DataTrigger>
                    </Style.Triggers>
                </Style>                    
            </StackPanel.Resources >
            <Label Content="Copying Files" Height="30" Width="100"/>
        </StackPanel >

1 个答案:

答案 0 :(得分:0)

您必须使用后台工作程序在处理时更新进度。

定义后台工作者:

 private BackgroundWorker SyncBgWorker = new BackgroundWorker();

为后台工作人员添加所需的事件

SyncBgWorker.DoWork += new DoWorkEventHandler(SyncBgWorkerOnDoWork);// the process should be here
            SyncBgWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);// if the process completed do this
            SyncBgWorker.ProgressChanged += worker_ProgressChanged;//while processing do this
SyncBgWorker.WorkerSupportsCancellation = false;
            SyncBgWorker.WorkerReportsProgress = true;//to get the progress 

事件/方法

 private void SyncBgWorkerOnDoWork(object sender, DoWorkEventArgs doWorkEventArgs)
        {
          //some codes
          SyncBgWorker.ReportProgress(10);//to update the progress value
         //some codes
          SyncBgWorker.ReportProgress(50);//to update the progress value
         //some codes
          SyncBgWorker.ReportProgress(100);//to update the progress value
        }

private void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            var objProgressBar = (ProgressBar)this.GetTemplateChild("PrgBarSyncProgress");
            UpdateProgressBarDelegate updatePbDelegate = new UpdateProgressBarDelegate(objProgressBar.SetValue);
            Dispatcher.Invoke(updatePbDelegate, System.Windows.Threading.DispatcherPriority.Background, new object[] { ProgressBar.TagProperty, "Synchronizing " + e.ProgressPercentage.ToString() + "%" });
        }

不要忘记更改进度条'PrgBarSyncProgress'的名称