繁体   English   中英

在这个简单的WPF应用程序中实现进度条

[英]Implement progressbar in this simple WPF application

我有MainWindow,它的视图模型为MainWindowViewModel。 在窗口内,有一个文本框可以接受用户的输入,还有几个单选按钮可以过滤搜索,还有一个按钮。 使用以下命令将按钮动作绑定到视图模型:

<Button x:Name="btnSearch" Command="{Binding SearchByCommand, Mode=OneWay}" />

在ViewModel内部有:

public ICommand SearchByCommand
{
    get
    {
        if (_SearchByCommand == null)
        {
            _SearchByCommand = new RelayCommand(
                x => this.LoadData(this.SearchBy),
                x => { return !string.IsNullOrEmpty(this.SearchText); }
            );
        }
        return _SearchByCommand;
    }
}

和LoadData:

private void LoadData(string searchBy)
{
   switch(searchBy)
   ...
}

这完美地工作,但是我不知道如何在此解决方案中实现进度条。 当用户单击搜索按钮时,进度条应启动进度并冻结当前UI。 用LoadData方法加载数据后,进度条的progresscount应该结束并再次启用UI。

您可以使用扩展的WPF工具箱中的busy指示器: 这里

然后,您需要在另一个线程中进行处理( LoadData ),以免冻结UI。 为此,简单的方法是使用后台工作程序:

向您的wm添加一个布尔值,以指示应用程序何时繁忙:

private bool isBusy;
public bool IsBusy
{
    get { return isBusy; }
    set
    {
        this.isBusy = value;
        this.OnPropertyChanged("IsBusy");
    }
}

设置后台工作者:

private void LoadData(string searchBy)
{
    IsBusy = true;
    BackgroundWorker worker = new BackgroundWorker();
    worker.DoWork += (o, ea) =>
    {
        //Do your heavy work here
    };

    worker.RunWorkerCompleted += (o, ea) =>
    {
        IsBusy = false;
    };

    worker.RunWorkerAsync();
}

如果要显示当前处理进度的进度条,则需要做更多的工作。 首先,您需要对忙碌指示器应用自定义样式:

<toolkit:BusyIndicator IsBusy="True" BusyContent="Processing..." >
    <extToolkit:BusyIndicator.ProgressBarStyle>
        <Style TargetType="ProgressBar">
            <Setter Property="IsIndeterminate" Value="False"/>
            <Setter Property="Height" Value="15"/>
            <Setter Property="Margin" Value="8,0,8,8"/>
            <Setter Property="Value" Value="{Binding ProgressValue}"/>
        </Style>
    </extToolkit:BusyIndicator.ProgressBarStyle>
</toolkit:BusyIndicator>

然后将一个ProgressValue属性添加到您的虚拟机:

private int progressValue ;
public int ProgressValue
{
    get { return progressValue ; }
    set
    {
        this.progressValue = value;
        this.OnPropertyChanged("ProgressValue ");
    }
}

并从后台工作者报告进度:

BackgroundWorker worker = new BackgroundWorker();
worker.WorkerReportsProgress = true;
worker.DoWork += (o, ea) =>
    {
        //Do your heavy work here
        worker.ReportProgress(10);

        //Do your heavy work here
        worker.ReportProgress(20);

        //And so on
    };

worker.ProgressChanged += (o,ea) =>
    {
        ProgressValue = e.ProgressPercentage;
    };

worker.RunWorkerCompleted += (o, ea) =>
    {
      IsBusy = false;
    };

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM