user8393563
user8393563

Reputation:

How do I use the backgroundworker with MVVM on startup without binding the command to a button?

The approch of my little WPF App is first to copy x files and the user shall see this on the progressbar. I only find ways to do it with a button which command is binded to the VM. Isn't there any possible way to call this all on startup without the use of a button?

Edit:

This is an example how I tried:

   public ViewModelDfsync()
    {
        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;
    }


    private readonly BackgroundWorker worker;
    private readonly RelayCommand instigateWorkCommand;

    // your UI binds to this command in order to kick off the work
    public RelayCommand InstigateWorkCommand
    {
        get { return this.instigateWorkCommand; }
    }

    private void DoWork(object sender, DoWorkEventArgs e)
    {
        // do time-consuming work here, calling ReportProgress as and when you can
        var files = Directory.GetFiles(@"C:\files");
        var destDir = @"C:\files\newDir";
        foreach (var file in files)
        {
            FileInfo fileName = new FileInfo(file);
            FileInfo destFile = new FileInfo(Path.Combine(destDir, fileName.Name));
            if (destFile.Exists)
            {
                if (fileName.LastWriteTime > destFile.LastWriteTime)
                {
                    fileName.CopyTo(destFile.FullName, true);
                    worker.ReportProgress(CurrentProgress);
                }
            }
            else
            {
                fileName.CopyTo(destFile.FullName);
                worker.ReportProgress(CurrentProgress);
            }
        }
    }

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


    private int currentProgress;
    public int CurrentProgress
    {
        get => currentProgress;
        private set
        {
            if (currentProgress != value)
            {
                currentProgress = value;
                RaisePropertyChanged("CurrentProgress");
            }
        }
    }

this is my progressbar in xaml:

<ProgressBar Minimum="0" Maximum="100" Value="{Binding CurrentProgress, Mode=OneWay}" Height="20"/>

Upvotes: 0

Views: 324

Answers (0)

Related Questions