gpt4 book ai didi

wpf - 使用带有 MVVM 模式的 WPF 实现进度条(使用 BackgroundWorker)

转载 作者:行者123 更新时间:2023-12-04 19:47:11 24 4
gpt4 key购买 nike

注意:此代码现在有效。我已经修复了一些愚蠢的错误,并且我还修改了 Steve Greatrex 指出的代码。

原贴链接How to implement a progress bar using the MVVM pattern

ProgressbarSampleView.xaml

  <UserControl x:Class="MyProject.ProgressbarSampleView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="718" Width="1024">

<ProgressBar Grid.Row="1"
Value="{Binding CurrentProgress, Mode=OneWay}"
Visibility="{Binding ProgressVisibility}"
Margin="22,0,25,0" />

<Button Grid.Row="2"
Content="Start Now"
Height="30"
Width="80"
HorizontalAlignment="Left"
Margin="22,4,0,0"
Name="btnStartNow"
VerticalAlignment="Top"
Command="{Binding Path=InstigateWorkCommand}"
/>
</UserControl>

进度条SampleViewModel.cs

  namespace MyProject
{
public class ProggressbarSampleViewModel: ViewModelBase
{
private readonly BackgroundWorker worker;
private readonly ICommand instigateWorkCommand;

public ProggressbarSampleViewModel()
{
this.instigateWorkCommand = new
RelayCommand(o => this.worker.RunWorkerAsync(), o => !this.worker.IsBusy);
this.worker = new BackgroundWorker();
this.worker.DoWork += this.DoWork;
this.worker.ProgressChanged += this.ProgressChanged;
}


public ICommand InstigateWorkCommand
{
get { return this.instigateWorkCommand; }
}

private int _currentProgress;
public int CurrentProgress
{
get { return this._currentProgress; }
private set
{
if (this._currentProgress != value)
{
this._currentProgress = value;
OnPropertyChanged("CurrentProgress");
}
}
}

private void ProgressChanged(object sender, ProgressChangedEventArgs e)
{
this.CurrentProgress = e.ProgressPercentage;
}

private void DoWork(object sender, DoWorkEventArgs e)
{
// do time-consuming work here, calling ReportProgress as and when you can
for (int i = 0; i < 100; i++)
{
Thread.Sleep(1000);
_currentProgress = i;
OnPropertyChanged("CurrentProgress");
}
}

}

最佳答案

StartNowCommand从不调用 BackgroundWorker - 它只是同步执行DoStartNow UI线程上的方法。基于此,我猜当您单击链接到 StartNow 的按钮时命令你看到你的用户界面卡住..?

您应该将按钮绑定(bind)到 InstigateWorkCommand实际运行 BackgroundWorker异步编码。

在这个实现中,我认为您不需要 StartNowCommand一点也不。我也没有看到 DoWork View 模型中任何位置的事件处理程序,所以我假设它只是调用 DoStartNow

关于wpf - 使用带有 MVVM 模式的 WPF 实现进度条(使用 BackgroundWorker),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7680422/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com