如何在 MVVM 中使用进度条

How to use Progressbar in MVVM

我真的坚持这一点。我在网上搜索了很多,但实际上没有任何帮助。在我看来,我有一个按钮和进度条,当用户单击按钮时,它会执行不同的工作,并且在增加 CurrentProgress.

之后

但它只在工作结束时向用户显示 100%,这不是我想要的。我希望每次 CurrentProgress 增加时它都会显示并显示到视图中。

视图中的控件是那些:

<Button x:Name="Generate" Content="Generate" />
<ProgressBar  Value="{Binding Path=CurrentProgress, Mode=OneWay}" Width="80" Height="15"/>

这是 ViewModel 中的代码

private int currentProgress;
public int CurrentProgress
{
    get { return currentProgress; }
    set
    {
        if (currentProgress == value)       
            return;

        currentProgress = value;
        NotifyOfPropertyChange(() => CurrentProgress);
    }
}

List<Article> articles;


public void Generate()
{
    foreach (var art in articles)
    {       
        //[..]
        //Insert article                    

        inserted++;

        Task.Factory.StartNew(() =>updateProgress(inserted));                    
    }

}


private void updateProgress(int Analyzed)
{
    if (Analyzed != 0)
    {
        int percentage = 100 * Analyzed / articles.Count;
        CurrentProgress = percentage;
    }   
}

如何解决这个问题?。提前感谢大家!

将 "Generate" 方法的全部内容放入任务中。然后您不需要执行任何特殊操作来更新进度,因为 "NotifyPropertyChanged" 事件由 WPF 在 UI 级别自动编组。 像这样:

Task.Factory.StartNew(() => {
    foreach (var art in articles)
    {       
        //[..]
        //Insert article                    

        inserted++;

        updateProgress(inserted);                    
    }
}