Guilian
Guilian

Reputation: 129

Pass a commandparameter to Backgroundworker in ViewModel WPF

there are many buttons on the Main window of my WPF-App. The commands of those buttons should have the same implementation/function but depending on which button has been pressed, the file/path on which the function accesses changes. How to detect which button was clicked from ViewModel using CommandParameter?How can I use this parameter in the method Dowork? In this example the CommandParameter of Button1 is called "button1" and that of Button2 is "button2".

Her is the code of the Backgroundworker in my ViewModel:

public ViewModel()
    {
        ...

        this.instigateWorkCommand = new DelegateCommand(o => this.worker.RunWorkerAsync(), o => !this.worker.IsBusy);
        this.worker = new BackgroundWorker();
        this.worker.DoWork += this.DoWork;
        this.worker.ProgressChanged += this.ProgressChanged;
        this.worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_Completeted);
        this.worker.WorkerReportsProgress = true;
    }

Her is the code of Dowork in my ViewModel:

private void DoWork(object sender, DoWorkEventArgs e)
    {
        // if (parameter.ToString().contains("button1")...
        // if (parameter.ToString().contains("button2")...
    }

Upvotes: 2

Views: 312

Answers (2)

Kishore Kumar
Kishore Kumar

Reputation: 12874

I would suggest, when you Run the worker using any of the buttons, pass the parameter as an object to your RunWorkerAsync(param) method.

Upvotes: 0

Jehof
Jehof

Reputation: 35544

Normally you use the RunWorkerAsync(object) method to pass parameters to your DoWork method.

this.worker.RunWorkerAsync("button1");

And in the DoWorkEventArgs the property Argument contains the value you passed into method RunWorkerAsync.

private void DoWork(object sender, DoWorkEventArgs e)
{
    if (e.Argument == "button1"){

    }
}

Upvotes: 2

Related Questions