In your ViewModel
you need to set up the BackgroundWorker
so that it reports progress back to the UI thread from the threadpool thread that runs your DoWork
method.
public class ViewModel : INotifyPropertyChanged
{
private BackgroundWorker worker;
private bool isLoading=false;
public ViewModel()
{
worker = new BackgroundWorker();
worker.WorkerReportsProgress = true;
worker.ProgressChanged += (sender, args) =>
{
int visibilitySetting = args.ProgressPercentage;
IsLoading = visibilitySetting == 0 ? false : true;
};
worker.DoWork += WorkerDoWork;
}
public bool IsLoading
{
get
{
return isLoading;
}
set
{
isLoading = value;
OnPropertyChanged();
}
}
private ICommand loadCommand;
public ICommand LoadCommand
{
get
{
return loadCommand ?? (loadCommand = new DelegateCommand(Load));
}
}
public void Load()
{
worker.RunWorkerAsync();
}
private void WorkerDoWork(object sender, DoWorkEventArgs e)
{
worker.ReportProgress(1);
Thread.Sleep(1500);
worker.ReportProgress(0);
}
In the Xaml
, place the ProgressBar
inside a fixed-sized Grid
so that the layout is not corrupted when the visibility changes. Bind the Visibility
property to the view model’s IsLoaded
property. Use the BooleanToVisibilityConverter
to enable it to bind to IsLoaded
. Something like this.
<Window x:Class="WpfProgress.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfProgress"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.Resources>
<BooleanToVisibilityConverter x:Key="boolToVisibilityConverter" />
</Window.Resources>
<Window.DataContext>
<local:ViewModel />
</Window.DataContext>
<Grid Background="white" Height="400" >
<StackPanel>
<TextBlock Text="uploading...." />
<Grid Height="30">
<ProgressBar x:Name="ProgressUpload" IsIndeterminate="True" Height="30" Width="328" VerticalContentAlignment="Center"
Visibility="{Binding Path=IsLoading, Converter={StaticResource boolToVisibilityConverter}}"/>
</Grid>
<Button x:Name="button" Content="Cancel Upload " Height="31" Width="127" Margin="10,25,0,0" Command="{Binding hello}" />
<Button Content="Upload " Height="31" Width="127" Margin=" 10,25,0,0" Command="{Binding LoadCommand}" />
</StackPanel>
</Grid>
</Window>