我有MainWindow,它有viewmodel MainWindowViewModel。窗口内有一个接受用户输入的文本框和几个用于过滤搜索的单选按钮和一个按钮。按钮操作使用如下命令绑定到viewmodel:
<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。
答案 0 :(得分:4)
您可以使用扩展WPF工具包中的忙指示符:here。
然后,您需要在另一个线程中进行处理(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属性添加到您的vm:
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;
};